我对以下代码有一些问题.我想将一个字符串显式化为一个对象,这是完全正常的,但是,如果此对象是泛型类的一部分,则失败并出现以下错误异常:"无法转换类型为'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) …Run Code Online (Sandbox Code Playgroud)