簡體   English   中英

如何在另一個通用基類上添加C#泛型類型約束?

[英]How to add a C# generic type constraint on another generic base class?

我已多次閱讀有關C#泛型類型參數約束的MSDN文檔,但我無法弄清楚如何執行此操作,或確定它是否可行。

假設我有一個這樣的通用基類:

public abstract class Entity<TId> { ... }

這個抽象基類沒有任何類型約束, TId可以是任何東西 - 結構,類等。

現在說我有一個通用的接口方法,我想將方法​​的泛型類型約束到上面的類:

public interface ICommandEntities
{
    void Update<TEntity>(TEntity entity) where TEntity : ?????;
}

我可以編譯這個:

public interface ICommandEntities
{
    void Update<TEntity, TId>(TEntity entity) where TEntity: Entity<TId>
}

...然而,我需要在執行方法時顯式添加兩個T1 ant T2泛型args:

commander.Update<AbcEntity, string>(abcEntity);

如果可能的話,我想讓編譯器推斷一切,這樣我就可以執行這樣的方法:

commander.Update(abcEntity);

這個活動可能嗎? 到目前為止,我可以使它工作的唯一方法是在泛型基類之上添加一個空的非泛型基類,並將其用作方法的類型約束:

public abstract Entity {}

public abstract EntityWithId<TId> : Entity { ... }

public interface ICommandEntities
{
    void Update<TEntity>(TEntity entity) where TEntity : Entity;
}

commander.Update(abcEntity);

...但最終我得到一個非常無用的類,充當標記界面。 這是擺脫這種泛型類和接口方法設計的唯一方法嗎? 或者我在這里遺漏了什么?

在檢查它編譯后,我會將其升級為答案。

從您的問題和評論中,您希望參數為Entity<Something> 您不需要將參數化類型直接用作類型,它可用於參數化參數。

所以就這么做

 public void Update(Entity<T1> entity) where ....

簡單的選擇是更改ICommandEntities的簽名:

public interface ICommandEntities
{
    void Update<TId>(Entity<TId> entity)
}

這有效地提供了您所追求的相同約束。

如注釋中所述,您應該只創建參數類型BaseClass<T>

class Program
{
    static void Main( string[] args )
    {
        ITest x = new TestClass();

        Console.WriteLine( x.GetTypeArgTypeFrom( new BaseClass<int>() ) );

        Console.ReadKey();

    }
}

public class BaseClass<T>
{
    public Type GetTypeArgType()
    {
        return typeof( T );
    }
}

public interface ITest
{
    Type GetTypeArgTypeFrom<T>( BaseClass<T> bct );
}

public class TestClass : ITest
{
    public Type GetTypeArgTypeFrom<T>( BaseClass<T> bct )
    {
        return bct.GetTypeArgType();
    }
}

暫無
暫無

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

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