我对以下代码有一些问题。我想为一个对象显式一个字符串,这工作得很好,但是,如果这个对象是一个泛型类的一部分,这将失败并出现以下错误异常:“无法转换类型为'System.String'的对象输入'test.B'”。即使我已经重载了该方法。
using System;
using System.Collections.Generic;
namespace test {
class Program {
static void Main(string [] args) {
// These two cast perfectly fine.
B x = (B) "abc";
C y = (C) "def";
A <B> a = new A<B>();
a.b();
A <C> b = new A<C>();
b.b();
}
}
class A<T> {
public List <T> a = new List<T>();
public void b() {
// Unable to cast object of type 'System.String' to type 'test.B'
this.a.Add ((T) (object) "abc");
this.a.Add ((T) (object) "def");
this.a.Add ((T) (object) "ghi");
}
}
class B {
public string b;
public static explicit operator B(string a) {
B x = new B();
x.b = a;
return x;
}
}
class C {
public string c;
public static explicit operator C(string a) {
C x = new C();
x.c = a;
return x;
}
}
}
如果有人能向我解释为什么这不是正确的投射,那就太棒了。
谢谢