[英]C#: How can I use reflection in order to cast an object?
public static void myMethod(Object myObject)
{
}
My object is of type SportCar. 我的对象是SportCar类型。 How can I create a new Object (Something like this)
我如何创建一个新的对象(类似这样的东西)
SportCart sportCar = myObject as SportCar
Later Edit: I don't know what is the type of myObject. 稍后编辑:我不知道myObject的类型是什么。 It could be SimpleCar, AbcCar etc
可能是SimpleCar,AbcCar等
This is generally where you would use an interface. 通常在这里使用接口。 In your case,
myMethod
must be doing something specific with the argument passed in. Lets take a simple example; 在您的情况下,
myMethod
必须对传入的参数进行特定的处理。 say myMethod
was responsible for starting the car, you would define an interface such as 例如说
myMethod
负责启动汽车,您将定义一个接口,例如
public interface ICar
{
void Start()
}
Then the argument to myMethod
would be of type ICar
rather than object
. 然后,
myMethod
的参数将为ICar
类型,而不是object
类型。
public void myMethod(ICar car)
{
car.Start();
}
Now mymethod
does not need to know (or care!!) what ICar
is presented, be it AbcCar, SportsCar etc. as long as that class implements ICar
现在
mymethod
并不需要知道(或关心!)什么ICar
呈现,无论是AbcCar,跑车等,只要是类实现ICar
public class SportsCar : ICar
{
public void Start()
{
Console.WriteLine("Vroom Vroom. SportsCar has started");
}
}
public class AbcCar : ICar
{
public void Start()
{
Console.WriteLine("Chug Chug. AbcCar has started");
}
}
It sounds like you want one of two things. 听起来您想要两件事之一。 Either have a base class
Car
or interface ICar that has all the shared behaviour that cars have and then you can do: 具有
Car
所有共享行为的基类Car
或ICar接口,然后可以执行以下操作:
ICar car = myObjectAsCar;
car.Drive(Speed.VeryFast);
Or, you want to do different things, depending on what type of car it is: 或者,您想要做不同的事情,具体取决于它是什么类型的汽车:
if (SportCar sporty = myObject as SportCar)
{
sporty.Drive(Speed.VeryFast);
}
if (HybridCar hybrid = myObject as HybridCar)
{
hybrid.Drive(Speed.Economical);
}
Do the car classes have a common type, and you just want to cast to that ie: 汽车类是否具有通用类型,而您只想强制转换为该类型,即:
BaseCar baseCar = myObject as BaseCar;
Or are you trying to examine the type first and then cast to the correct type, ie: 或者您是要先检查类型,然后将其转换为正确的类型,即:
if(myObject is SimpleCar)
{
var simpleCar = myObject as SimpleCar;
}
If you're thinking of doing the second, I strongly recommend you use the first. 如果您打算进行第二次操作,强烈建议您使用第一项。 And if you're using the first you don't need to worry about what type of car it is.
而且,如果您使用的是第一辆车,则无需担心它是哪种类型的汽车。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.