按类型动态访问属性
本文关键字:属性 访问 动态 类型 | 更新日期: 2023-09-27 18:00:31
我正试图访问一个与传递到泛型中的属性类型相同的属性。
看看代码:
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
}
如果你不能从代码中看到。基本上,我希望能够将某个东西传递到泛型中,然后访问与传递的东西类型相同的类上的属性。
有什么好方法可以做到这一点吗?如果你需要澄清,请告诉我。。。
您可以使用反射和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);
如果只有一个这样的属性可以实现:
var prop = typeof(CustomClass).GetProperties().First(p => p.PropertyType == typeof(T));
object value = prop.GetValue(@class, null);
可以使用SetValue
:设置值
object valueToSet = ...
prop.SetValue(@class, valueToSet);