C# PropertyInfo 获取实体类属性名称和属性值

本文介绍了如何在C#中使用反射来获取和操作对象的属性。通过具体实例展示了生成Type对象的不同方式,并演示了如何利用PropertyInfo来获取实体类的所有属性及特定属性的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

*

#region 生成Type类的对象:方式一
Type type = typeof(Student);
#endregion

#region 生成Type类的对象:方式二
Type typeStudent2 = new Student().GetType();
#endregion

1、调用

public void Get()
{
    User model = new User
    {
        user_name = "admin",
        nick_name = "king",
        password = "123456"
    };
    string result = GetProperties(model);
    string value = GetPropertyValue(model, "user_name");
}

2、实体类

public class User
{
    public string user_name { get; set; }
    public string nick_name { get; set; }
    public string password { get; set; }
}

3、PropertyInfo 获取实体类的所有属性和值

public string GetProperties<T>(T t)
{
    string tStr = string.Empty;
    if (t == null)
    {
        return tStr;
    }
    PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

    if (properties.Length <= 0)
    {
        return tStr;
    }
    foreach (PropertyInfo item in properties)
    {
        string name = item.Name;
        object value = item.GetValue(t, null);
        if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
        {
            tStr += string.Format("{0}:{1},", name, value);
        }
        else
        {
            GetProperties(value);
        }
    }
    return tStr;
}

4、PropertyInfo 获取实体类指定属性值

public string GetPropertyValue<T>(T t, string field)
{
    string value = "9";
    if (t == null)
    {
        return value;
    }
    PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

    if (properties.Length <= 0)
    {
        return value;
    }
    var property = properties.Where(x => x.Name == field).FirstOrDefault();
    value = property.GetValue(t, null).ToString();

    return value;
}

5、类型判断
propertyInfo.PropertyType != typeof(int)
propertyInfo.PropertyType != typeof(double)
propertyInfo.PropertyType != typeof(DateTime?)


private readonly TestDbContext _context;

public ReportsService(TestDbContext context)
{
    _context = context;
}

public IEnumerable<TestDto> Get()
{
    _context.ExecuteProc<TestDto>("存储过程名称", 参数);
}

public static IEnumerable<TElement> ExecuteProc<TElement>(this TestDbContext db, string sql, params object[] parameters) where TElement : new()
{
    var connection = db.Database.GetDbConnection();
    using (var cmd = connection.CreateCommand())
    {
        db.Database.OpenConnection();
        cmd.CommandText = sql;
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Parameters.AddRange(parameters);
        var dr = cmd.ExecuteReader();
        var columnSchema = dr.GetColumnSchema();
        var data = new List<TElement>();
        while (dr.Read())
        {
            TElement item = new TElement();
            Type type = item.GetType();
            foreach (var kv in columnSchema)
            {
                var propertyInfo = type.GetProperty(kv.ColumnName);
                if (kv.ColumnOrdinal.HasValue && propertyInfo != null)
                {
                    if (kv.ColumnName == "COLLECTOR_CODE")
                    { }
                    var value = dr.IsDBNull(kv.ColumnOrdinal.Value) ? null : dr.GetValue(kv.ColumnOrdinal.Value);
                    if (value == null)
                    { }
                    else
                    {
                        if (!string.IsNullOrEmpty(value.ToString())
                            && propertyInfo.PropertyType != typeof(int)
                            && propertyInfo.PropertyType != typeof(double)
                            && propertyInfo.PropertyType != typeof(DateTime?))
                        {
                            value = value.ToString();
                        }
                    }
                    propertyInfo.SetValue(item, value);
                }
            }
            data.Add(item);
        }
        dr.Dispose();
        return data;
    }
}

6、所有字符串字段中,删除前导空格和尾随空格

public static void TrimStringFields<T>(this T obj) where T : class
{
    if (obj is null) return;
    var stringProperties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                    .Where(p => p.PropertyType == typeof(string));

    foreach (var property in stringProperties)
    {
        var propertyValue = (string?)property.GetValue(obj);
        if (propertyValue != null)
        {
            var trimmedValue = propertyValue.Trim();
            property.SetValue(obj, trimmedValue);
        }
    }
}

// 调用
public async Task<AppSrvResult<long>> CreateAsync(MenuCreationDto input)
{
    input.TrimStringFields();
}

*
*
*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值