簡體   English   中英

泛型泛型或類型參數的推斷和繼承

[英]Generic Generics or Type argument inference and inheritance

我正在嘗試使用.Net 4.5 C#中的泛型做一些事情,老實說,我不確定這是否可行或被稱為什么。 這使搜索變得更加困難。

無論如何,最好用一個例子來解釋。

假設我有一些界面:

public interface ISomeBase {}

及其實現的例子

public class AnObject : ISomeBase {}

public class AnOtherObject : ISomeBase {}

然后我得到了ClassA,它具有一些類似的通用方法

public class ClassA
{
    public T SomeMethod1<T>() where T : class, ISomeBase
    {
        //Do some stuff and return some T
        return default(T);
    }

    public List<T> SomeMethod2<T>(Expression<Func<T,object>> someExpression ) where T : class, ISomeBase
    {
        //Do some stuff and return some List<T>
        return new List<T>();
    }

}

我希望能夠像這樣使用它(很容易就能做到):

public class SomeImplementation
{
    public void Test()
    {
        var obj = new ClassA();
        var v = obj.SomeMethod1<AnObject>();
        var v2 = obj.SomeMethod2<AnOtherObject>((t) => t.ToString());
    }
}

但是我也希望能夠像這樣使用它(由於需要使用類型實參,因此無法正常工作。我知道ClassB中的T與Class A中每個方法中的T不同:

public class ClassB<T> : ClassA where T: ISomeBase
{
    public T Tester()
    {
       //This is not possible and requires me to add a Type argument. 

        return SomeMethod1(); //I would like to leave out the type argument and have the compiler infer what it is

        // Some of the time I want to be able to apply the same type to all methods on ClassA. 
        // And some of the time I want to be able to specify the type arguments on a per method basis
    }
}

我想避免將ClassA包裝成這樣的東西:

public class ClassA<T> : ClassA where T : class, ISomeBase
{
    public T SomeMethod1()
    {
        return SomeMethod1<T>();
    }

    public List<T> SomeMethod2(Expression<Func<T, object>> someExpression)
    {
        return SomeMethod2<T>(someExpression);
    }
}

我一直在尋找和閱讀所有可以動手的東西。 但是似乎沒有合適的選擇。 也許我沒有使用正確的術語進行搜索,因為說實話,我不知道它叫什么。

任何幫助或指針將不勝感激。

您沒有為編譯器提供足夠的信息來推斷它應該使用的類型參數。

類型推斷是一個非常復雜的過程,但是,通常,如果方法類型參數未出現在參數列表中,則不會對該類型參數執行類型推斷。 您可能需要閱讀C#規范 了解類型推斷的詳細信息。

希望有人可以進一步澄清。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM