从Activator获取变量/属性.调用CreateInstance对象
本文关键字:调用 CreateInstance 对象 属性 Activator 获取 变量 | 更新日期: 2023-09-27 18:13:55
下面是我的代码:
public class Test
{
string a;
int b;
}
public class Test2
{
string c;
string d
int e;
}
我正在将其编译为DLL并提取两个类:
var library = Assembly.LoadFrom(libraryPath);
IEnumerable<Type> types = library.GetTypes();
,然后"foreach类型的类型",我想得到我的变量列表,但不知道如何做到这一点…我正在尝试:
var lib = Activator.CreateInstance(type);
Type myType = lib.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
// Do something with propValue
}
"props"一直是空的…
有什么帮助吗
你的类没有指定任何属性。它们指定私有字段。这意味着:
- 您需要呼叫
GetFields
,而不是GetProperties
- 您需要指定
BindingFlags.NonPublic | BindingFlags.Instance
,以便为您提供非公共实例字段
当然,你也可以把你的类改成public属性
您显示的不是属性而是字段-因此您需要调用myType.GetFields()
。对于私有字段等,您需要使用适当的BindingFlags
进行调用。
我想你的意思是
var instance = Activator.CreateInstance(myType);
FieldInfo[] fields = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
object value = field.GetValue(instance);
// Do something with field value...
}
要获取字段列表,您需要使用GetFields。
要获得方法列表,你需要使用GetMethods。
要获得属性列表,您需要使用GetProperties。
要获取事件列表,你需要使用GetEvents。
…在这种情况下你不需要创建一个列表,你确定你需要创建一个列表吗?你可以直接使用数组,它总是返回一个副本。