在C#中,除了对同一泛型的更多类约束外,还有什么替代方法?

在C#中,除了对同一泛型的更多类约束外,还有什么替代方法?,c#,generics,C#,Generics,考虑到以下结构: public class A { public int Prop { get; set; } } public class B { public int Prop { get; set; } } public static class Extension { public static int Sum<T>(T template, int input) where T : A { return template.P

考虑到以下结构:

public class A
{
    public int Prop { get; set; }
}

public class B
{
    public int Prop { get; set; }
}

public static class Extension
{
    public static int Sum<T>(T template, int input) where T : A
    {
        return template.Prop + input;
    }
}
但这不起作用,它会产生:

已为类型参数“T”指定了约束子句。必须在单个where子句中指定类型参数的所有约束

编辑


我不需要寻找两个独立类类型的通用参数,但我正在寻找一种方法,将这两种类型的相同功能分配给单个参数。

您可以创建包装器类:

public class Wrapper
{
    private A a;
    private B b;        

    public Wrapper(A a)
    {
        this.a = a;
    }

    public Wrapper(B b)
    {
        this.b = b;
    }

    public int Prop { get { return (int)(a?.Prop ?? b?.Prop); } }
}

public static class Extension
{
    public static int Sum(this Wrapper template, int input)
    {
        return template.Prop + input;
    }
}
用法:

var a = new A();
var result = (new Wrapper(a)).Sum(2);
//or
var b = new B();
result = (new Wrapper(b)).Sum(2);
var a = new A();
var result = ((Wrapper)a).Sum(2);
//or
var b = new B();
result = ((Wrapper)b).Sum(2);
借助于显式转换,还有另一种解决方案:

用法:

var a = new A();
var result = (new Wrapper(a)).Sum(2);
//or
var b = new B();
result = (new Wrapper(b)).Sum(2);
var a = new A();
var result = ((Wrapper)a).Sum(2);
//or
var b = new B();
result = ((Wrapper)b).Sum(2);

为什么一开始就使用泛型?只需使用方法重载:

public static int Sum(A template, int input) { ... }

public static int Sum(B template, int input) { ... }
为了避免重复代码,只需委托实现:

public static int Sum(A template, int input) { return add(A.Prop, input); }
public static int Sum(B template, int input) { return add(B.Prop, input); }
private static int add(int prop, int input) { ... }

阅读您的帖子,减少重复代码的唯一方法是:

public static class Extension
{
    public static int Sum(A template, int input)
    {
        return Sum(template.Prop, input);
    }

    public static int Sum(B template, int input)
    {
        return Sum(template.Prop, input);
    }

    static int Sum(int templateProp, int input) 
    {
        return templateProp + input;
    }
}

这是假设您的方法中有更复杂的逻辑。

是否必须仅限于A和B?@Dandré是的,只有
A
B
,这是唯一的约束,但两者都是具体的类。多个约束表示“和”,或“或”
T:A
T:B
意味着T同时扩展了A和B。您不能扩展两个类。您可以编写两个方法
Sum
:一个用于
A
,另一个用于
B
@SlavaUtesinov您的观点很好,但这就是我想指定具体类型为
A
B
的原因,因为我不想重复代码这是所有其他方法中全新的,但我的问题的答案是,它是重复的,不可能达到泛型类型以拥有多个可能的具体类。我决定取消标记这个答案,因为它需要在构造函数中复制代码。。。我很抱歉,但我在尝试实现它时才意识到这一点,因为当前的示例简而言之就是我实际面临的情况。我将有很多重复的代码。@然后简单地委托给实现逻辑的第三个方法。参见editsThis这是一个很好的方法,但是我有很多属性和一些逻辑来计算它们,所以它们都需要通过一个不够干净的方法的参数发送。我必须在
Sum
方法中保留逻辑。但是前两个方法仍然是重复的代码。。。的确,减少了!