有没有一种方法可以为一个泛型参数合并多个继承,而这对于两个相同的类方法是相同的



这两个泛型参数是相同的,但我有两个不同的方法,它们使用两个不同类型的泛型参数约束。我正试图通过使用泛型来简化代码量。


public static void thisClass.MainMethod<T1, T2>() where T1 : Control where T2 : TextBoxBase
{
thisClass.FirstMethod<T1>(object x);  // where T : Control is needed for ((T)x).OneMethod();
thisClass.SecondMethod<T2>(object x); // where T : TextBoxBase is needed for ((T)x).TwoMethod();
}

该类是一个静态类,包含所有方法有没有办法将其简化为以下内容?

public static void thisClass.MainMethod<T1>(object control) where T1 : Control, TextBoxBase
{
thisClass.FirstMethod<T1>(object objControl);
thisClass.SecondMethod<T1>(object objControl);
//more code here
}

EDIT:这里是FirstMethod和SecondMethod的样子,以防有帮助

public static void FirstMethod<T1>(object objControl) where T : Control
{
//some code here
string someStringVariableNeededInThisMethod = ((T1)objControl).Text; //not just this specific method needs to be called
//more code here
}
public static void SecondMethod<T1>(object objControl) where T : TextBoxBase
{
//some code here
((T1)objControl).AcceptsTab() = true; //not just this specific method needs to be called
//more code here
}

C#自动将派生类的对象视为基类的实例。事实上,在这种情况下,您根本不需要泛型。

下面是一个例子。把Base看作Control,把Derived看作TextBoxBase(继承自Control(:

using System;
namespace ConsoleApp3
{
public class Base
{
public int BaseInt { get; private set; } = 0;
public void IncrementBaseInt() => BaseInt++;
}
public class Derived : Base
{
public void PrintBaseInt() => Console.WriteLine($"{BaseInt}");
}
public static class Foo
{

public static void BaseMethod(Base argument) => argument.IncrementBaseInt();

public static void DerivedMethod(Derived argument) => argument.PrintBaseInt();
public static void Method(Derived argument) 
{
DerivedMethod(argument);
BaseMethod(argument);
DerivedMethod(argument);
}
}
internal class Program
{
static void Main(string[] args)
{
Derived derivedArgument = new ();
Foo.Method(derivedArgument);
}
}
}

该程序先打印0,然后打印1。但请注意,我本可以用Derived作为参数类型来编写BaseMethod的签名,它也会做完全相同的事情。

最新更新