有没有一种方法可以告诉方法泛型具有哪种类型?我想要做的是告诉方法它只能是 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)
并且只有一个 if - case 和一个铸造。只有方法多于基类的那个。
编辑:
想象一下你会有这样一个结构:
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();
}
}
这种方法或现象称为多态性
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句