簡體   English   中英

使用函數傳遞的自定義類型創建字典C#

[英]Creating Dictionary C# with custom type passed by function

我想創建一個字典,其中TKey為字符串,TValue來自於編譯時不知道的類型。

假設我有一個功能

 createDict(Type type)
 {
     Dictionary<string, {here's the type from the func. argument}> dict = new Dictionary..

 }

這是可能的情況還是我缺少一些非常基本的東西?

如果將type作為參數傳遞,則可以完成此操作:

var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string),type);
var dictionary = (IDictionary)Activator.CreateInstance(dictionaryType);

由於您對本詞典中所插入內容的正確性承擔全部責任,因此使用此類詞典將更加困難。

使方法通用:

public void CreateDict<T>()
{
    Dictionary<string,T> dict = new Dictionary<string,T>();

}

盡管您可能希望返回類型也為Dictionary<string,T>並將約束添加到泛型類型參數。

您將其稱為:

CreateDict<MyCustomType>();

上面假設類型可以在編譯時傳入。

您可以進行一些反思:

Type dict = typeof (Dictionary<,>);
Type[] parameters = {typeof (string), type};
Type parametrizedDict = dict.MakeGenericType(parameters);
object result = Activator.CreateInstance(parametrizedDict);

所有實例和類都是對象,所以為什么不使用Dictionary<string,object>並且使用與MVC,Session或Cache中的ViewData相同的方式進行轉換,它們都需要轉換。

如果在編譯時知道類型,則使用泛型:

void Main()
{
    var dict = CreateDict<int>();
    dict["key"] = 10;
}

Dictionary<string, T> CreateDict<T>()
{
    return new Dictionary<string, T>();
}

如果不是,請重構為使用基本類型或接口,例如:

var dic = new Dictionary<string, IMyType>();

IMyType公開了您希望保留在字典中的類型的常見特征。

我只有在萬不得已的情況下才會反思。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM