![](/img/trans.png)
[英]Type.GetType(“{namespace.classname}{assemblyname}”) not working in c#
[英]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.