Dor*_*sje 7 c# generics casting explicit
我对以下代码有一些问题.我想将一个字符串显式化为一个对象,这是完全正常的,但是,如果此对象是泛型类的一部分,则失败并出现以下错误异常:"无法转换类型为'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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果somone可以向我解释为什么这不正确,那将是非常棒的.
谢谢
转换运算符仅在静态知道类型时应用; 毕竟,泛型方法需要为每个使用完全相同的ILT - 因此在某些情况下它不能调用您的运算符,而在其他情况下则不能调用类型检查.
另外,因为你已明确地转换为object,所以永远不会使用它; 从铸造object是总是一个简单的拆箱或类型检查.
一个邪恶的解决方案是(我不喜欢这个):
this.a.Add((T)(dynamic)"abc");
this.a.Add((T)(dynamic)"def");
this.a.Add((T)(dynamic)"ghi");
Run Code Online (Sandbox Code Playgroud)
这将决议推迟到运行时.它有效,但我需要在那之后洗眼睛.但更一般地说:运算符和泛型不能很好地运行 - 所以:尽量不要在API中使用这种组合.我个人真的不会用上面的!
| 归档时间: |
|
| 查看次数: |
1606 次 |
| 最近记录: |