简体   繁体   English

在 C# 中创建通用字典

[英]Creating Generic Dictionary in C#

I am trying to add a Key value pair the key is a string and the value is a class.我正在尝试添加一个键值对,键是字符串,值是 class。 The whole is thing is accesses through a generic method.整个事情是通过通用方法进行访问。 So when I do a search based on the Key I get the class value in the dictionary.因此,当我根据 Key 进行搜索时,我会在字典中得到 class 值。 But unfortunately the code I have written compile it gives the below error.但不幸的是,我编写的代码编译它给出了以下错误。 TokenizeCardViewModel' is a type, which is not valid in the given context TokenizeCardViewModel' 是一种类型,在给定的上下文中无效

So when I do something like this:所以当我做这样的事情时:

bool value = CreditCardDetailPathCollection().Contains(subPathValue)

I Should get true or false.我应该得到真或假。 So that I can later use the value of the dictonary to create instance of the class.这样我以后可以使用字典的值来创建 class 的实例。

private Dictionary<string,T> CreditCardDetailPathCollection<T>() where T:class
{
   return new Dictionary<string,T>
   { 
      { "tokenize-card", TokenizeCardViewModel } 
   };
}

Try this code试试这个代码

private Dictionary<string, T> CreditCardDetailPathCollection<T>() where T : class
    {
        var obj = Activator.CreateInstance<T>(); 
        return new Dictionary<string, T>
        { 
            { "tokenize-card", obj } 
        };
    }

Below code will create the instance of the T下面的代码将创建 T 的实例

var obj = Activator.CreateInstance<T>();

This way you just need to call the CreditCardDetailPathCollection method like this这样你只需要像这样调用 CreditCardDetailPathCollection 方法

var dict = CreditCardDetailPathCollection<TokenizeCardViewModel>();

Let's see if I understand that problem.让我们看看我是否理解这个问题。

  1. You have a K/V pair which is actually a string / Type .你有一个 K/V 对,它实际上是一个string / Type
  2. Given a key , you are returned a Type .给定一个key ,您将返回一个Type
  3. Given the type , you now create an instance of this type.给定type ,您现在创建此类型的实例。

Here's some code that might help...这是一些可能有帮助的代码...

NOTE: I also made this little .NET Fiddle so you can see it in action注意:我还制作了这个小 .NET Fiddle ,这样你就可以看到它的实际效果

var myTypes = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
myTypes.Add("Leia", typeof(User));

...

if (!myTypes.ContainsKey(key))
{
    Console.WriteLine($"Dictionary failed to contain the key: {key}");
    return;
}

var myType = myTypes[key];
Console.WriteLine($"Found the type: ${myType.ToString()}.");

try
{
    var something = Activator.CreateInstance(myType);
}
catch (Exception exception)
{
    Console.WriteLine($"Failed to create an instance of {myType.ToString()}. Why? Error Message: {exception.Message}");
}

Now this assumes that there is a default constructor for the class which you wish to dynamically create an instance of.现在假设您希望动态创建其实例的 class 有一个default constructor

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

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