2025-03-28 09:49:56 +08:00

48 lines
1.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
namespace DataTransferService.Method
{
public abstract class EntityBase
{
/// <summary>
/// 索引器,可以用字符串访问变量属性
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <returns>属性值如果传入的属性名称不存在返回null</returns>
public object this[string propertyName]
{
get
{
//从所有获取的属性值中找到传入的属性值
var pi = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).FirstOrDefault(p => p.Name.ToUpper().Equals(propertyName.ToUpper()));
if (null != pi && null != pi.GetMethod)
{
return pi.GetValue(this);
}
else
{
return null;
}
}
set
{
var pi = this.GetType().GetProperties().FirstOrDefault(p => p.Name.ToUpper().Equals(propertyName.ToUpper()));
if (null != pi && null != pi.SetMethod)
{
if (pi.PropertyType.Equals(value.GetType()))
{
pi.SetValue(this, value);
}
else
{
pi.SetValue(this, Convert.ChangeType(value, pi.PropertyType));
}
}
}
}
}
}