在 C# 中使用泛型类型作为参数



有没有一种方法可以告诉方法泛型具有哪种类型? 我想做的是告诉方法它只能是 A 或 B 类型的对象,而不能是其他对象,所以我可以在


if (myObject.GetType() == typeof(myTypeA)){doAstuff();} if (myObjectGetType() == typeof(myTypeB)) {doBstuff();}

method<T>(T myObject){ T = myTypeA, T = myTypeB, T = nothing else}

感谢您的任何帮助

您可以在方法中检查类型,然后将其转换为适当的类型并执行适当的"操作":

public void method<T>(T myObject)
{
if (myObject is myTypeA)
{
myTypeA objA = myObject as myTypeA;
objA.DoA_Stuff();
}
else if (myObject is myTypeB)
{
myTypeB objB = myObject as myTypeB;
objB.DoB_Stuff();
}
else
{
return ;
}
}

但那将是对泛型的浪费。如果它们共享一些方法,您还可以创建一个基类,并让 typeA 和 typeB 从中继承。然后,您的方法可以将基类对象作为参数:

public void method(BaseClass myObject)

并且只有一个如果 - 案例和一个铸造。只有具有更多方法的基类。

编辑:

想象一下,你会有这样一个结构:

public class BaseType
{
public int SharedProp { get; set; } // shared property 
public virtual int DoSharedStuff() // shared method
{
return SharedProp;
}    
}
public class myTypeA : BaseType
{
public int A_Prop { get; set; }
// overwritten shared meth adjusted to the needs of type A
public override int DoSharedStuff() 
{
return base.SharedProp + this.A_Prop;
}
}
public class myTypeB : BaseType
{
public int B_Prop { get; set; }
// overwritten shared meth adjusted to the needs of type B
public override int DoSharedStuff()
{
return base.SharedProp + this.B_Prop;
}
// individual method of Type B
public int DoB_Stuff()
{
return this.B_Prop;
}
}

然后,您的方法将只获取基类的一个子级并根据需要执行:

public void method(BaseType myObject)
{
// shared case: here type A will perform type A action 
// and type B will perform type B action
myObject.DoSharedStuff();
// case B where you need really the extra stuff!
if (myObject is myTypeB)
{
myTypeB objB = myObject as myTypeB;
objB.DoB_Stuff();
}
}

这种方法或现象称为多态性

您可以使用 where 命令限制 gernic 允许的类型:

public void Test<T>(T param) where T : TypeA {
...
}

https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/keywords/where-generic-type-constraint

但这只是简单的约束,因此它不能解决两个类的问题,但在这种情况下,您可以使用方法重载:

public void Test(TypeA param) {
...
}
public void Test(TypeB param) {
...
}

如果你只有两个类,我认为这是最好的解决方案,因为泛型没有任何好处。

最新更新