鉴于评论中的解释,为什么你认为你需要这个:不,
你不需要排除int
来自泛型类型。
当类中的重载方法(仅参数类型不同的方法)在泛型类中使用时,则已经决定调用哪个方法,而泛型类独立于具体类型进行编译,然后在以后使用在。
Example:
class Test<T>
{
public void Trigger(T test)
{
// Will always call Internal(object) and never call Internal(int) even when T is int.
Internal(test);
}
private void Internal(int test)
{
MessageBox.Show("Triggered int");
}
private void Internal(object test)
{
MessageBox.Show("Triggered object");
}
}
private void buttonTest_Click(object sender, EventArgs e)
{
Test<int> test = new Test<int>();
test.Trigger(42);
}
输出是
“触发对象”
即使当T
is int
,超载的Internal
方法需要一个int
从未被调用,因为该决定Trigger
称为Internal
期望的方法object
已经为整个泛型类制作了,与所使用的具体类型无关。
当您使用OrderedDictionary
内部。myOrderedDictionary[x]
where x
是一种泛型类型将始终使用按键访问条目的索引属性,而不是按顺序访问条目的索引属性,因为这一决定是基于泛型类型的已知约束做出的,与稍后使用的具体类型无关。
class TestDictionary<TKey, TValue>
{
OrderedDictionary orderedDictionary = new OrderedDictionary();
public void Add(TKey key, TValue value)
{
orderedDictionary.Add(key, value);
}
public TValue GetByIndex(int index)
{
return (TValue)orderedDictionary[index];
}
public TValue GetByKey(TKey key)
{
return (TValue)orderedDictionary[key];
}
}
private void buttonTest_Click(object sender, EventArgs e)
{
TestDictionary<int, string> test = new TestDictionary<int, string>();
test.Add(42, "Test");
MessageBox.Show(test.GetByIndex(0)); // Correct output "Test"
MessageBox.Show(test.GetByKey(42)); // Correct output "Test"
}