簡體   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