【问题标题】:Reflection c# in a set property在集合属性中反射 c#
【发布时间】:2014-04-22 00:08:09
【问题描述】:

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

set
    {
        Type t = value.GetType();

        if (dictionaries[int.Parse(value.GetType().ToString())] == null)
        {
            dictionaries[int.Parse(value.GetType().ToString())] = new Dictionary<string,t>();
        }
    }

它无法识别我的 Dictionary 构造函数中的单词 t。 我究竟做错了什么?我该如何解决?

【问题讨论】:

  • 您能提供完整的属性定义吗?

标签: c# reflection types properties set


【解决方案1】:

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

void SetDict<T>(T value)
{
    Type t = typeof(T);
    if (dictionaries[t.FullName] == null)
    {
        dictionaries[t.FullName] = new Dictionary<string,T>();
    }
}

除了使用类型名称,您还可以将Type 值直接用作字典的键:

Dictionary<Type, Dictionary<string,T>> dictionaries;

您可以在不指定泛型类型参数的情况下调用它,因为编译器可以推断类型。但是,这仅适用于静态类型,不适用于运行时类型。 IE。您必须使用正确类型的表达式而不是通过像 object 这样的基本类型来调用该方法。

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

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

注意:泛型类型参数允许您在编译时创建强类型的专用类型和方法。强类型的优势在于编译器和 IDE 可以为您提供有关类型的信息并证明您的代码在编译时是静态正确的。在 RUNTIME 创建泛型类型没有任何优势,因为您将无法在编译时(或设计时,如果您愿意)使用它的优势。您也可以使用Dictionary&lt;string, object&gt; 等。

请在代码审查中查看我的答案:Type-safe Dictionary for various types。特别是我对答案的更新。

【讨论】:

    【解决方案2】:

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

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

    Type t = ....
    var x = new Dictionary<string, t>();
    

    根据你的班级,你可以这样做:

    public class Something<T>
    {
        public T Value
        {
            ...
            set
            {
                ... new Dictionary<string, T>();
            }
        }
    }
    

    但这并不完全相同。

    你还有一个不同的问题,这个:

    int.Parse(value.GetType().ToString())
    

    不会工作。

    value.GetType().ToString()
    

    可能会产生类似System.Int32YourAssembly.NameSpace.SomeType 的东西,而不是可以解析的数字。

    我认为你需要退后一步,弄清楚你要在这里完成什么。

    【讨论】:

    • 我解决了你说我解决不了的问题(我不需要使用实际类型)。关于 int.parse() - 我知道 - 我已经修复了它,我没有问它,因为它没有满。现在我有另一个问题 - 我无法指定属性的类型,因为它是未知的。不知道有没有办法:|
    猜你喜欢
    • 2010-11-21
    • 2011-07-25
    • 2017-05-31
    • 1970-01-01
    • 2023-04-10
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    相关资源
    最近更新 更多