繁体   English   中英

在C#2.0 .net中使用Type.GetType(string),但找不到类型或名称空间名称't'

[英]use Type.GetType(string) in C# 2.0 .net but type or namespace name 't' could not be found

我不确定该如何解决。 我有

public void get_json(String TYPE)
{
    Type t = Type.GetType("campusMap." + TYPE); 
    t[] all_tag = ActiveRecordBase<t>.FindAll();
}

但是我总是得到

错误9找不到类型或名称空间名称“ t”(您是否缺少using指令或程序集引用?)C:_SVN_ \\ campusMap \\ campusMap \\ Controllers \\ publicController.cs 109 17 campusMap

关于为什么要定义我希望访问的类型的任何想法都说它不起作用? 我尝试使用反射来做到这一点,但没有运气。 有人能够提供解决方案示例吗?

[编辑]可能的解决方案

这是试图使用反射,所以我将传递字符串并使用泛型调用方法。

        public void get_json(String TYPE)
        {
            CancelView();
            CancelLayout();
            Type t = Type.GetType(TYPE);
            MethodInfo method = t.GetMethod("get_json_data");
            MethodInfo generic = method.MakeGenericMethod(t);
            generic.Invoke(this, null);
        }
        public void get_json_data<t>()
        {
            t[] all_tag = ActiveRecordBase<t>.FindAll();
            List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();
            foreach (t tag in all_tag)
            {
                JsonAutoComplete obj = new JsonAutoComplete();
                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;
                tag_list.Add(obj);
            }
            RenderText(JsonConvert.SerializeObject(tag_list)); 
        }

我得到的错误是..

        obj.id = tag.id;

的“ t”不包含“ id”的定义

和两个名字一样。

您不能将变量作为通用参数传入:

t[] all_tag = ActiveRecordBase<t>.FindAll();

它在抱怨<t>部分。 你不能那样做。

我建议您检查一下: 如何使用反射调用泛型方法?

除此之外,我可能会使用泛型方法对泛型进行所有您想做的事情,然后使用反射使用运行时类型变量来调用泛型函数。

public void get_json<t>()
{
    t[] all_tag = ActiveRecordBase<t>.FindAll();
    //Other stuff that needs to use the t type.
}

然后使用链接的SO答案中的反射技巧来调用带有泛型参数的get_json函数。

MethodInfo method = typeof(Sample).GetMethod("get_json");
MethodInfo generic = method.MakeGenericMethod(typeVariable);
generic.Invoke(this, null);

您的程序表明对C#的工作原理有基本的误解。 在编译程序之前 ,编译器必须同时知道all_tag的类型和type参数的类型值。 在程序已经运行之前(显然是编译之后) ,您才需要确定该类型。

您不能将静态编译时类型与动态运行时类型混合在一起。 一旦使用了反射功能, 整个过程就必须使用反射功能。

您可以将类型的选择委托给调用代码吗? 您不能将运行时类型指定为通用的编译时类型,但是如果可以将类型的选择委派给调用者,则可以完成所需的操作。

public ??? get_json<T>() // seems like this should return something, not void
{
     var collection = ActiveRecord<T>.FindAll();
     // do something with the collection
}

称为

get_json<CampusMap.Foo>();

即使您在编译时不知道类型,通过反射来调用这种方法也 可能 会更容易,请参见https://stackoverflow.com/a/232621

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM