我需要访问诸如 strClassname.strPropertyName
之类的东西 我将在程序执行中为 strClassname
和 strProperty
名称设置不同的值。
请指引我正确的方向。
最佳答案
在我看来,您正试图在运行时获取(或设置)对象的属性值。所以这是执行此操作的最基本方法:
public static object GetPropertyValue(object instance, string strPropertyName)
{
Type type = instance.GetType();
System.Reflection.PropertyInfo propertyInfo = type.GetProperty(strPropertyName);
return propertyInfo.GetValue(instance, null);
}
...并设置一个值:
public static void SetPropertyValue(object instance, string strPropertyName, object newValue)
{
Type type = instance.GetType();
System.Reflection.PropertyInfo propertyInfo = type.GetProperty(strPropertyName);
propertyInfo.SetValue(instance, newValue, null);
}
如果你试图获取一个类的属性名称,这里有一个函数:
public static IEnumerable<string> GetPropertyNames(string className)
{
Type type = Type.GetType(className);
return type.GetProperties().Select(p => p.Name);
}
假设您有 100 个对象,并且您想要获取每个对象的 Name 属性的值,这里有一个函数可以完成此操作:
public static IEnumerable<String> GetNames(IEnumerable<Object> objects, string nameProperty = "Name")
{
foreach (var instance in objects)
{
var type = instance.GetType();
var property = type.GetProperty(nameProperty);
yield return property.GetValue(instance, null) as string;
}
}
关于c# - 在 C# 中动态访问类及其属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13985261/