Ale*_*lex 4 .net c# reflection casting explicit-conversion
当发现以下代码在运行时抛出异常时,我感到很惊讶:
class A
{
public string Name { get; set; }
public A()
{
Name = "Class A";
}
}
class B
{
public string Name { get; set; }
public B()
{
Name = "Class B";
}
public static explicit operator A(B source)
{
return new A() {Name = source.Name};
}
}
class Program
{
static void Main(string[] args)
{
// This executes with no error
var bInstance = new B();
Console.WriteLine(bInstance.GetType()); // <assemblyname>.B
var aInstance = (A) bInstance;
Console.WriteLine(aInstance.Name); // Class B
// This fails with InvalidCastException
var bInstanceReflection = Activator.CreateInstance(typeof (B));
Console.WriteLine(bInstanceReflection.GetType()); // <assemblyname>.B
var aInstanceReflection = (A) bInstanceReflection;
Console.WriteLine(aInstanceReflection.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我为什么?我真的不明白发生了什么
你不应该感到惊讶 - 自定义操作符不会覆盖任何东西,它们会重载 - 所以它们是在编译时选择的,而不是执行时间.
当我们从代码中删除隐式类型时,它会使它更清晰:
object bInstanceReflection = Activator.CreateInstance(typeof (B));
Console.WriteLine(bInstanceReflection.GetType()); // <assemblyname>.B
A aInstanceReflection = (A) bInstanceReflection;
Run Code Online (Sandbox Code Playgroud)
现在很明显,在最后一行中,(A)只是一个object执行正常引用转换的强制转换.根本不会应用用户定义的转换.
如果您使用的是.NET 4,则可以使用动态类型来使其工作:
// Note the change of type
dynamic bInstanceReflection = Activator.CreateInstance(typeof (B));
Console.WriteLine(bInstanceReflection.GetType()); // <assemblyname>.B
A aInstanceReflection = (A) bInstanceReflection;
Run Code Online (Sandbox Code Playgroud)
现在转换正在应用于动态值,这意味着选择要使用的转换延迟到执行时间 - 此时它将使用您的自定义运算符.