繁体   English   中英

c# 其中对于泛型类型约束 class 可能不是

[英]c# where for generic type constraint class may NOT be

我想排除一些在通用 class 中使用的类型。我知道如何进行约束以确保通用类型是某种(接口)类型。 但我似乎无法弄清楚如何排除(多种)类型。

例如:我想要一个通用的 class 来排除 ints 和 uints(但是不排除 DateTime,例如,所以不是所有的 Primitives 都可以被排除)。

我不能做这样的事情:

public class SomeWhereTest2<T> where T : !System.Int32 
{ 
}

有人可以帮我解决如何一次排除多种类型吗?


我制作了一个特殊的 class ,它就像一本字典,也是一个带有索引的 FiFo 集合,其中 0 是最近的值,1 是前一个值等。( public class FiFoDictionary<K, V>: IDictionary<K, V> ,它使用OrderedDictionary作为内部字典。)

但是由于索引是通过int给出的,因此当字典的键是int时会出现问题。 因为那样你会得到链接到键的值,而不是索引。 或者有什么方法可以强制使用索引而不是OrderedDictionary的键?

鉴于评论中的解释,为什么你认为你需要这个:不,你不需要从通用类型中排除int

当 class 中的重载方法(仅参数类型不同的方法)在泛型 class 中使用时,已经决定调用哪个方法,而泛型 class 独立于具体类型进行编译,然后稍后使用在。

例子:

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);
}

output 是

“触发对象”

即使Tint ,采用int的重载Internal方法也永远不会被调用,因为Trigger调用期望objectInternal方法的决定已经针对整个泛型 class 做出,与所使用的具体类型无关。


在内部使用OrderedDictionary时也是如此。 myOrderedDictionary[x] where x is a generic type will always use the index property that accesses by key 而不是按顺序访问它们的属性,因为这一决定是基于通用类型的已知约束而独立于所使用的具体类型稍后的。

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"
}

C# 中没有这样的东西,但是您可以 scope 通用类型以一种可以帮助您实现它的方式。 这只是一个示例,我不认为这是解决您问题的方法

class MyGeneric<T> where T : new() { } // T must be a class with default constructor
class MyGeneric<T> where T : System.IComparable<T> { }// T must implement IComparable interface 
class MyGeneric<T> where T : System.IComparable<T>, new () { }

它不可能做到,不能使用 The.= 和 == 运算符,因为不能保证具体类型参数将支持这些运算符。 在这里你可以阅读更多关于

暂无
暂无

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

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