0
List<int>
で指定せずにtest
がList<>
であることを指定できますか?С#FieldTypeが一部のリストであることの反射チェック
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>();
}
}
}
こんにちは、([このstackoverflowの質問]この音似た思いhttps://stackoverflow.com/questions/1043755/c-sharp-generic- list-t-how-to-type-of-t) –
リスト形式を文字列として保存する:\t \t \t string listName = typeof(List <>); ToString(); LISTNAME = listName.Substring(0、listName.Length - 3); //ドロップは、[T] 次いで – rmbq
場合@rmbq:いいえ、行わない(item.ToString()(リスト名)が含まれています。)それ。このようなことを目的として設計されたリフレクションのメソッドを使用してください...ここの答えやリンクされた複製を見てください。 – Chris