C# 想要创建一个类型为 Dictionary<int, T> 的自定义类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/963068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Want to create a custom class of type Dictionary<int, T>
提问by mrblah
I want to create a custom class that basically wraps a dictionary.
我想创建一个基本上包装字典的自定义类。
I want to add a property to it called Name.
我想向它添加一个名为 Name 的属性。
I tried:
我试过:
public class MyDictionary<int, T> : Dictionary<int, T>
{
public string Name { get; set;}
}
Doesn't seem to be working, any ideas?
似乎不起作用,有什么想法吗?
Update
更新
THe error I'm getting is:
我得到的错误是:
Type parameter declaration must be an identifier not a type
回答by John Saunders
The problem is with your declaration. Your custom class only needs a single type parameter, since the int
type never varies:
问题出在你的声明上。您的自定义类只需要一个类型参数,因为int
类型永远不会改变:
public class MyDictionary<T> : Dictionary<int, T>
{
public string Name { get; set; }
}
回答by Vinod Srivastav
If you can wrap the dictionary, then why not this:
如果您可以包装字典,那么为什么不这样做:
public class Context<T>
{
private Dictionary<int, T> dictContext;
public String Name { get; private set; }
public Context (String name)
{
this.Name = name;
dictContext = new Dictionary<int, T>();
}
And you can add all dictionary members:
您可以添加所有字典成员:
public int Count {
get { return dictContext.Count(); }
}
public Dictionary<int, T>.KeyCollection Keys
{
get { return dictContext.Keys; }
}
public Dictionary<int, T>.ValueCollection Values
{
get { return dictContext.Values; }
}
public void Add (int key, T value)
{
dictContext.Add(key, value);
}
public bool Remove (int key)
{
return dictContext.Remove(key);
}
and declare your own
并声明你自己的
public void MyFunction ()
{
//do nothing
}
}