按类型动态访问属性

时间:2014-04-28 19:43:34

标签: c# .net generics

我试图访问与传递给通用符的类型相同的属性。

查看代码:

class CustomClass
{
    CustomProperty property {get; set;}
}

class CustomProperty
{
}

Main
{
        // Create a new instance of my custom class
        CustomClass myClass = new CustomClass();

        // Create a new instance of another class that is the same type as myClass.property
        CustomProperty myProp = new CustomProperty();

        // Call the generic method 
        DynamicallyAccessPropertyOnObject<CustomProperty>(myProp, myClass);
}


private void DynamicallyAccessPropertyOnObject<T>(this T propertyToAccess, CustomClass class)
{
    // I want to access the property (In class) that is the same type of that which is passed in the generic (typeof(propertyToAccess))

    // TODO: I need help accessing the correct property based on the type passed in
}

如果您无法从代码中看到。基本上我希望能够将某些内容传递给泛型,然后在与传入的内容类型相同的类上访问该属性。

这样做有好办法吗? 如果您需要澄清,请告诉我......

2 个答案:

答案 0 :(得分:5)

您可以使用反射和LINQ

private static void DynamicallyAccessPropertyOnObject<T>()
{
    var customClass = typeof(CustomClass);
    var property = customClass
                  .GetProperties()
                  .FirstOrDefault(x => x.PropertyType == typeof(T));

}

如果您仅为CustomClass执行此操作,则可以删除这两个参数。然后您可以调用它:

DynamicallyAccessPropertyOnObject<CustomProperty>();

如果要概括它,请使用两个通用参数:

private static void DynamicallyAccessPropertyOnObject<T, K>(K targetObj)
{
    var targetType = targetObj.GetType();

    var property = targetType
                  .GetProperties()
                  .FirstOrDefault(x => x.PropertyType == typeof(T));

    if(property != null) 
    {
       var value = (T)property.GetValue(targetObj);
    }
}

然后叫它:

DynamicallyAccessPropertyOnObject<CustomProperty,CustomClass>(myClass);

答案 1 :(得分:1)

如果只有一个这样的属性,你可以这样做:

var prop = typeof(CustomClass).GetProperties().First(p => p.PropertyType == typeof(T));
object value  = prop.GetValue(@class, null);

您可以使用SetValue设置值:

object valueToSet = ...
prop.SetValue(@class, valueToSet);