【发布时间】:2018-01-11 06:36:56
【问题描述】:
是否可以指定test 为List<> 而不指定List<int> 的条件类型?
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
SuperClass1 class1 = new SuperClass1();
PrintAllFields(class1);
}
public static void PrintAllFields(object obj)
{
var SuperClassType = obj.GetType();
foreach (var item in SuperClassType.GetFields())
{
if (item.FieldType == typeof(List<>))
{
Console.WriteLine("it's List");
}
else if (item.FieldType == typeof(Int32))
{
Console.WriteLine("it's int32");
}
else if (item.FieldType == typeof(Byte))
{
Console.WriteLine("it's byte");
}
}
}
}
public class SuperClass1
{
public int param1;
public int param2;
public int param3;
public byte param4;
public List<int> test;
public SuperClass1()
{
test = new List<int>();
}
}
}
更新:
我使用了相关答案中的函数,现在代码看起来像。而且它不能正常工作。我希望收到控制台消息Console.WriteLine("it's List");,但似乎我做错了。如何解决这个问题?因为我认为这个问题与相关问题中的问题不同。
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
SuperClass1 class1 = new SuperClass1();
PrintAllFields(class1);
}
public static void PrintAllFields(object obj)
{
var SuperClassType = obj.GetType();
foreach (var item in SuperClassType.GetFields())
{
if (IsInstanceOfGenericType(typeof(List<>), item))
{
Console.WriteLine("it's List");
}
else if (item.FieldType == typeof(Int32))
{
Console.WriteLine("it's int32");
}
else if (item.FieldType == typeof(Byte))
{
Console.WriteLine("it's byte");
}
}
}
public static bool IsInstanceOfGenericType(Type genericType, object instance)
{
Type type = instance.GetType();
while (type != null)
{
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == genericType)
{
return true;
}
type = type.BaseType;
}
return false;
}
}
public class SuperClass1
{
public List<int> test = new List<int>();
public SuperClass1()
{
test = new List<int>();
}
}
}
【问题讨论】:
-
嗨,这听起来类似于this stackoverflow question
-
将列表类型保存为字符串:string listName = typeof(List).ToString(); listName = listName.Substring(0, listName.Length - 3);//drop [T] then if(item.ToString().Contains(listName))
-
@rmbq:不,不要那样做。使用为此类事情设计的反射方法...请参阅此处的答案或链接的副本。
-
@Chris 我尝试了你的解决方案,但没有为我工作......也许我做错了什么
-
@rmbq:那么你的代码有问题。
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)将正确识别该类型是否为通用列表。为什么它不适合你?我不知道,我看不到你的代码。 ideone.com/05zNiR 将清楚地证明该技术是合理的。
标签: c# reflection