繁体   English   中英

如何使用反射动态获取对象属性的实例

[英]How to dynamically get the instance of an object's property using reflection

我发现了很多例子,ALMOST告诉我我需要知道的内容。 但是到目前为止,所有内容都假设我已经有一个要设置值的属性实例。 但是我没有实例。 我有一个PropertyInfo对象。 我可以动态获取属性的名称,但是为了调用SetValue(),我必须具有该属性的实例才能传递给方法。 如何获取需要设置其值的属性的实例? 这是我的代码??? 必须提供属性实例的位置。 如何获取属性的实例,而不仅仅是PropertyInfo对象? (我之所以编写此方法,是因为我不能保证各种存储过程将返回哪些列。)

protected new void MapDbResultToFields(DataRow row, DataColumnCollection columns)
{
    Console.WriteLine("Entered Clinician.MapDbResultToFields");
    var properties = this.GetType().GetProperties();
    Console.WriteLine("Properties Count: " + properties.Length);
    foreach (DataColumn col in columns)
    {
        Console.WriteLine("ColumnName: " + col.ColumnName);
    }
    foreach (var property in properties)
    {
        string propName = property.Name.ToLower();
        Console.WriteLine("Property name: " + propName);
        Console.WriteLine("Index of column name: " + columns.IndexOf(propName));
        Console.WriteLine("column name exists: " + columns.Contains(propName));
        if (columns.Contains(propName))
        {
            Console.WriteLine("PropertyType is: " + property.PropertyType);
            switch (property.PropertyType.ToString())
            {
                case "System.String":
                    String val = row[propName].ToString();
                    Console.WriteLine("RowColumn Value (String): " + val);
                    property.SetValue(???, val, null);
                    break;
                case "System.Nullable`1[System.Int64]":
                case "System.Int64":
                    Int64.TryParse(row[propName].ToString(), out var id);
                    Console.WriteLine("RowColumn Value (Int64): " + id);
                    property.SetValue(???, id, null);
                    break;
                case "System.Boolean":
                    Boolean.TryParse(row[propName].ToString(), out var flag);
                    Console.WriteLine("RowColumn Value (Boolean): " + flag);
                    property.SetValue(???, flag, null);
                    break;
            }

        }
        else
        {
            Console.WriteLine("Property name not found in columns list");
        }
    }
}

您错误地认为您需要尝试设置的属性的实例,但是实际上您需要在其上设置属性的对象的实例。 属性在其所属的对象之外没有生命。

property.SetValue(this, val, null);

最有可能是您想要的东西。

由于您正在获取THIS ..的属性,因此您实际上具有要设置的对象的实例。 设置时只需使用THIS关键字。

像这样获取属性时

var properties = this.GetType().GetProperties();

您可以像这样设置属性

foreach(var property in properties)
{
    property.SetValue(this, id, null);
}

如果您尝试从没有实例的对象获取属性,则此方法将无效。

var properties = SomeObject.GetType().GetProperties();

希望这能回答您的问题!

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM