集合属性中的反射c#

集合属性中的反射c#,c#,reflection,types,properties,set,C#,Reflection,Types,Properties,Set,当我试图获取值的类型时,为什么不能在集合属性中使用值字 set { Type t = value.GetType(); if (dictionaries[int.Parse(value.GetType().ToString())] == null) { dictionaries[int.Parse(value.GetType().ToString())] = new Dictionary<string,t&g

当我试图获取值的类型时,为什么不能在集合属性中使用值字

set
    {
        Type t = value.GetType();

        if (dictionaries[int.Parse(value.GetType().ToString())] == null)
        {
            dictionaries[int.Parse(value.GetType().ToString())] = new Dictionary<string,t>();
        }
    }
set
{
类型t=value.GetType();
if(字典[int.Parse(value.GetType().ToString())]==null)
{
字典[int.Parse(value.GetType().ToString())]=newdictionary();
}
}
它不认识我字典里的t这个词。
我做错了什么?如何解决它?

在声明泛型类型时,不能使用
类型
变量,必须使用实际类型

换句话说,这是行不通的:

Type t = ....
var x = new Dictionary<string, t>();
这是行不通的

value.GetType().ToString()
很可能会生成类似于
System.Int32
YourAssembly.NameSpace.SomeType的内容,而不是可以解析的数字


我认为您需要后退一步,找出您在这里要实现的目标。

您不能将类型的值或名称用作泛型类型参数。请改用具有泛型类型参数的方法:

void SetDict<T>(T value)
{
    Type t = typeof(T);
    if (dictionaries[t.FullName] == null)
    {
        dictionaries[t.FullName] = new Dictionary<string,T>();
    }
}
您可以在不指定泛型类型参数的情况下调用它,因为编译器可以推断类型。但是,这仅适用于静态类型,而不适用于运行时类型。也就是说,必须使用正确类型的表达式调用该方法,而不是通过基本类型(如
object
)调用该方法

SetDict("hello"); // ==> string type
SetDict(42); // ==> int type

object obj = "world";
SetDict(obj); // ==> object type, not string type!

注意:泛型类型参数允许您在编译时创建强类型专用类型和方法。强类型的优点在于编译器和IDE可以为您提供有关类型的信息,并证明您的代码在编译时是静态正确的。在运行时创建泛型类型没有任何优势,因为您将无法在编译时(或者如果愿意,在设计时)使用它的优势。您也可以使用
字典
或类似工具


请参阅我关于代码审查的回答:。特别是我对答案的更新。

您能提供完整的属性定义吗?我解决了您说我无法解决的问题(我不需要使用实际类型)。关于int.parse()-我知道-我已经修复了它,我没有问它,因为它没有满。现在我有另一个问题-我无法指定属性的类型,因为它是未知的。我不知道是否有解决方案:|
void SetDict<T>(T value)
{
    Type t = typeof(T);
    if (dictionaries[t.FullName] == null)
    {
        dictionaries[t.FullName] = new Dictionary<string,T>();
    }
}
Dictionary<Type, Dictionary<string,T>> dictionaries;
SetDict("hello"); // ==> string type
SetDict(42); // ==> int type

object obj = "world";
SetDict(obj); // ==> object type, not string type!