通用明确的转换失败C# [英] Generic explicit cast failure C#
问题描述
我已经用下面这段代码的一些问题。我想明确的字符串到一个对象,这是工作完全正常,但是,如果这个对象是一个通用类的一部分,这是一个具有以下错误异常失败:无法投类型的对象'System.String'键入test.B'。 。即使我重载方法
I've some issues with the following piece of code. I would like to explicit a string to an object, this is working perfectly fine, however, if this object is part of a generic class, this is failing with the following error exception: "Unable to cast object of type 'System.String' to type 'test.B'". Even though I've overloaded the the method.
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;
}
}
}
这将是真棒,如果有人为可这是为什么不正确铸件向我解释。
It would be awesome if somone could explain to me why this isn't casting properly.
感谢
推荐答案
转换运营商,只有当类型是静态已知适用;毕竟,通用的方法,需要使用完全一样的IL 每 T
- 所以它不能打电话给你的运营商在某些情况下,和类型检查他人。
Conversion operators only apply when the type is known statically; after all, generic methods need to use the exact same IL for every T
- so it can't call your operator in some cases, and a type-check in others.
此外,因为你的明确投地对象
,将绝不会中使用;从对象
是总是的一个简单的拆箱和类型检查。
Additionally, because you've explicitly cast to object
, it will never be used; a cast from object
is always a simple unbox or type check.
这是邪恶的铸造修复将是(我不喜欢这个):
An evil fix would be (and I don't like this):
this.a.Add((T)(dynamic)"abc");
this.a.Add((T)(dynamic)"def");
this.a.Add((T)(dynamic)"ghi");
会推迟分辨率运行时。它的工作原理,但我需要后洗我的眼睛。更一般地,虽然:运营商和仿制药的没有发挥很好的 - 所以:尽量不要使用该组合你的API中。 我的真正的将不会使用上面,个人!
which defers the resolution to runtime. It works, but I would need to wash my eyes after that. More generally, though: operators and generics do not play nicely - so: try not to use that combination in your API. I really wouldn't use the above, personally!
这篇关于通用明确的转换失败C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!