假设我们有一些类没有通用的接口或基类。我们如何获得想要的班级名称?可能吗?我发现以下代码可以正常工作。但是,我想通过传递类名在函数中使用它。还有其他方法可以实现吗?
MemberInfo[] members = typeof(objectWhatever).GetMembers();
foreach (MemberInfo memberInfo in members.Where(p => p.MemberType == MemberTypes.Property))
{
Console.WriteLine("Name: {0}", memberInfo.Name); // Name: MyField
}
我尝试编写以下内容,但在语法上不起作用。
public static List<string> FieldNames(object obj ,string className)
{
dynamic changedObj = Convert.ChangeType(obj, Type.GetType(className));
MemberInfo[] members = typeof(changedObj).GetMembers();
foreach (MemberInfo memberInfo in members.Where(p => p.MemberType == MemberTypes.Property))
{
Console.WriteLine("Name: {0}", memberInfo.Name); // Name: MyField
}
}
答案 0 :(得分:1)
我相信你想要
MemberInfo[] members = Type.GetType(className).GetMembers();
typeof()
仅适用于已知的编译时类型-对于通用类型,例如typeof(string)
或typeof(T)
。
如果您正要这样做,那么您也不需要更改 obj
的类型即可使用反射来查看其成员的值。
答案 1 :(得分:1)
首先,我们必须找到给定名称的Type
,例如
// className either in short format: "Form" or
// in full format: "System.Windows.Forms.Form"
private static Type TypeFromName(string className)
{
if (string.IsNullOrWhiteSpace(className))
return null;
return AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(asm => asm.GetTypes())
.FirstOrDefault(t => t.Name == className || t.Namespace + "." + t.Name == className);
}
然后我们准备枚举 properties :唯一的区别是我们使用tp
-Type
found 而不是 hardcoded typeof(objectWhatever)
string className = ...
Type tp = TypeFromName(className);
if (tp != null)
{
var members = tp
.GetMembers()
.Where(p => p.MemberType == MemberTypes.Property);
foreach (MemberInfo memberInfo in members)
{
Console.WriteLine("Name: {0}", memberInfo.Name);
}
}
else
{
// className has not been found
}