真正的问题是反射和装配修补/挂钩.我将举一个简单的例子来展示我的问题,而不是太难理解主要问题.
所以让我们想象一下我有这些基本类:
public class Vehicle
{
public string Name;
public string Price;
public void DoSomething()
{
Main.Test(this);
}
}
public class Car : Vehicle
{
public int Wheels;
public int Doors;
}
Run Code Online (Sandbox Code Playgroud)
在主要代码上我运行它:
public class Main
{
public void Start()
{
Car testCar = new Car()
{
Name = "Test Car",
Price = "4000",
Wheels = 4,
Doors = 4
};
testCar.DoSomething();
}
public static void Test(Vehicle test)
{
// Is this allowed ?
Car helloWorld = (Car) test;
}
}
Run Code Online (Sandbox Code Playgroud)
好的,问题是:
是否允许转换(在静态方法测试中)?我会失去汽车的属性,但保留车辆属性?
如果它是错的,有没有其他方法可以做到这一点?
谢谢.
的演员Vehicle,以Car只允许当对象传入恰好是Car.否则你会得到一个例外.
有一个强制转换,当类型错误时不会导致异常:
Car car = test as Car;
Run Code Online (Sandbox Code Playgroud)
这不会抛出,但是当Vehicle是不是一个Car,变量car会null.您可以添加一个if条件来测试转换是否成功:
Car car = test as Car;
if (car != null) {
...
}
Bus bus = test as Bus;
if (bus != null) {
...
}
Rv rv = test as Rv;
if (rv != null) {
...
}
Run Code Online (Sandbox Code Playgroud)
但是,C#提供了一个更好的解决方案:方法重载可以让你完全避免投射.
public class Main {
public static void Test(Car test) {
... // This method will be called by Main.Test(this) of a Car
}
public static void Test(Bus test) {
... // This method will be called by Main.Test(this) of a Bus
}
public static void Test(Rv test) {
... // This method will be called by Main.Test(this) of an Rv
}
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为编译器this在进行Main.Test(this)调用时知道变量的确切类型.
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |