是否可以将对泛型对象的引用传递到不同的类型中
本文关键字:类型 引用 泛型 是否 对象 | 更新日期: 2023-09-27 17:58:56
我有一个方法,我想接受对特定对象的引用:
public static void Death(ref Animal unit)
{
...
}
然后我有:
object target
一个通用对象,可以是Animal和其他东西。如果是动物,我想把目标投射到动物中,然后把这个ref传给我的死亡方法,但我不知道怎么做…
如果您的意思是更改ref参数不会影响target
,您可以像这样手动更新。
Animal animal = target as Animal;
if(animal != null)
{
Death(ref animal);
target = animal;//Update it manually to target
}
Animal a = target as Animal;
if(a != null)
{
Death(ref a);
}
编辑:如果你想在Death
中修改target
,唯一的方法是在那里进行检查:
public static void Death(ref object unit)
{
Animal a = unit as Animal;
if(a != null)
{
//assign unit
}
}