从模型属性中检索值会在 C# 中引发“对象与目标类型不匹配”

问题描述 投票:0回答:1

我正在尝试从 Identity User 模型中检索属性信息。用户模型中的数据来自数据库或 API,这是

从控制器中,我通过从数据库发送用户名来检索数据。将值发送到 GetAttribute(typeof(Users)); 以检索属性信息。

    public async Task<ActionResult<Users>> get_attibutes(string userName)
    {
        var users = await _userManager.FindByNameAsync(userName);
        
        GetAttribute(typeof(Users));
        
        return Ok(); 
    } 

GetAttribute() 函数是:

        public static void GetAttribute(Type t)
        {
            PropertyInfo[] propertiesInfo = t.GetProperties();
            foreach (PropertyInfo propertyInfo in propertiesInfo)
            {
                if (!string.IsNullOrEmpty(propertyInfo.Name)) 
                {
                    string propery_name = propertyInfo.Name;
                    string property_type = propertyInfo.PropertyType.Name;

                    string property_value = propertyInfo.GetValue(t);     // Object does not match target type

                    Console.WriteLine($"Attribute Name: { propery_name } , type: { property_type }, value: { property_value }");
                }

            }
        } 

从上面的代码可以完美找到属性名称和类型,但在检索属性值时出现错误对象与目标类型不匹配

string property_value = propertyInfo.GetValue(t);

我想要实现的是获取每个属性名称、属性值和属性类型。这是最终结果。

Property_Name : FirstName
Property_value: Tazbir
Property_type : string

我正在尝试找到适当的解决方案,但这需要时间。 预先感谢。

c# asp.net asp.net-core attributes system.reflection
1个回答
0
投票

您正在尝试获取类型

property
上的
t
的值,而不是
instance
type

public static void GetAttribute(object obj)
{
    Type t = obj.GetType();
    PropertyInfo[] propertiesInfo = t.GetProperties();
    foreach (PropertyInfo propertyInfo in propertiesInfo)
    {
        if (!string.IsNullOrEmpty(propertyInfo.Name)) 
        {
            string propery_name = propertyInfo.Name;
            string property_type = propertyInfo.PropertyType.Name;

            // Here, pass the instance `obj` to GetValue, not the type `t`.
            object property_value = propertyInfo.GetValue(obj, null); 

            Console.WriteLine($"Attribute Name: { propery_name }, type: { property_type }, value: { property_value }");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.