这是我的代码:
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 type in types”,我想获取我的变量列表,但不知道该怎么做......我正在尝试:
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
}
“ Prop ”一直是空的...
有什么帮助吗?
最佳答案
您的类没有指定任何属性。他们指定私有(private)字段。这意味着:
- 您需要调用
GetFields
,而不是GetProperties
- 您需要指定
BindingFlags.NonPublic | BindingFlags.Instance
以便为您提供非公开实例字段
当然,您也可以将类更改为具有公共(public)属性。
关于c# - 从 Activator.CreateInstance 对象获取变量/属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035400/