次のコードに問題があります。オブジェクトに文字列を明示したいのですが、これは完全に正常に機能していますが、このオブジェクトがジェネリック クラスの一部である場合、次のエラー例外で失敗します:「タイプ '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;
}
}
}
これが適切にキャストされない理由を誰かが説明してくれたら最高です。
ありがとう