1

In developing a class that should handle various generic lambda expressions, I fell into a rather familiar hole: I had a MyClass<T> class, and I tried to cast MyClass<string> to MyClass<object>, like so:

MyClass<string> myClassString = GetMyClass(); // Returns MyClass<String>
MyClass<object> myClassObject = myClassString;

Doing so returned an compilation error saying there there's no implicit conversion between the two types, but that an explicit conversion does exist. So I added the explicit conversion:

MyClass<object> myClassObject = (MyClass<object>)myClassString;

Now the code compiled, but failed in runtime, claiming the conversion is illegal.

I am using Visual Studio 2012, and the code is part of a Portable Class Library project compiled with C# 5.

Just to make sure, I replaced MyClass IList - the same behavior appeared - an explicit conversion is allowed, but fails during run-time.

Why? Why does the compiler accept this? What's the point of the explicit conversion if it fails in runtime?


If Condition not Working ASp.Net?

i am trying to check condition before entering into it but it is entering in wrong condition

my conditions are ,

 if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() == "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)

if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() != "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) > 10000000)

the values are,

T_B_CX = 0 and T_B_C = 2500000000

it must enter the fist condition i mentioned but it is entering in second condition???

Hopes for your suggestion thanks in advance

4

4 回答 4

5

为了允许强制转换,您需要将其标记为协变。但是,协方差只允许用于接口(和委托)。这看起来像:

interface MyInterface<out T> ...

您可以编译显式转换的原因可能是编译器假定的返回值GetMyClass()可能是 a MyClass<object>。但是,如果没有声明,这很难说。

于 2013-07-07T13:19:59.590 回答
3

为了能够投MyClass<string>给您,MyClass<object>您需要满足以下条件:

  • MyClass<T>必须是接口,例如IMyClass<T>.
  • 您需要将out关键字添加到类型参数T,使类型参数协变
  • 类型参数T只能出现在接口成员的输出位置。

例如:

public interface IMyClass<out T>
{
    T GetItem();    // T in an output position
}

现在你可以投射它:

IMyClass<string> myClassString;
IMyClass<object> myClassObject = (IMyClass<object>)myClassString;
于 2013-07-07T13:22:34.890 回答
0

如果您有 A 类和 B 类,并且您想将 B 转换为 A,则以下条件之一必须为真:

  • B 派生/实现 A 或反之亦然
  • 有一个从 B 到 A 定义的显式转换运算符

在你的情况下,以上都不是真的,所以演员表是无效的。

如果您的类实现 IEnumerable 您可以使用扩展方法

using System.Linq
...
MyClass<Object> asObject = GetMyClass().Cast<Object>();

否则,编写一个显式的运算符或函数来进行转换:

public MyClass<Base> ConvertToBase<Base, Derived>(MyClass<Derived>) where Derived : Base
{
    // construct and return the appropriate object
}
于 2013-07-07T13:24:07.223 回答
-2

使用转换运算符来实现你的类到另一个类的转换

http://msdn.microsoft.com/en-us/library/85w54y0a.aspx

http://msdn.microsoft.com/en-us/library/09479473(v=vs.80).aspx

于 2013-07-07T13:30:37.887 回答