本文介绍了如何在另一个通用基类上添加C#通用类型约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有关C#泛型类型参数约束的MSDN文档,但是我无法弄清楚如何做到这一点,或者无法确定它是否可行.

I've read the MSDN documentation on C# generic type parameter constraints several times, but I cannot figure out how to do this, or determine if it's even possible.

说我有一个像这样的通用基类:

Say I have a generic base class like this:

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

此抽象基类没有任何类型约束,TId可以是任何东西-结构,类等.

This abstract base class does not have any type constraints, TId can be anything -- a struct, class, etc.

现在说我有一个通用接口方法,我想将方法​​的通用类型限制为上述类:

Now say I have a generic interface method, and I want to constrain the generic types on the method to the above class:

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:

...however then I need to explicitly add both T1 ant T2 generic args when executing the method:

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

如果可能的话,我想让编译器推断所有内容,以便我可以执行如下方法:

If possible, I would like to make the compiler infer everything, so that I can execute the method like this:

commander.Update(abcEntity);

此事件可能吗?到目前为止,使它起作用的唯一方法是在通用基类之上添加一个空的非通用基类,并将其用作方法的类型约束:

Is this event possible? So far the only way I can get it to work is by adding an empty, non-generic base class above the generic base class and using it as a type constraint on the method:

public abstract Entity {}

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

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

commander.Update(abcEntity);

...但是最后我得到了一个无用的类,它充当了标记接口.这是摆脱这种通用类&的唯一方法.接口方法设计?还是我在这里想念东西?

... but then I end up with a pretty useless class that acts as a marker interface. Is that the only way to get away with this type of generic class & interface method design? Or am I missing something here?

推荐答案

检查其编译后,我将其升级为答案.

After checking that it compiles, I will upgrade it to an answer.

根据您的问题和评论,您希望参数为Entity<Something>.您无需将参数化类型直接用作类型,可以将其用于参数化.

From your question and comments, you want the parameter to be Entity<Something>. You do not need to use the parametrized types directly as a type, it can be use to parametrize a parameter.

所以就做

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

这篇关于如何在另一个通用基类上添加C#通用类型约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 22:10