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?


Showing launcher screen only once in Android

I want to show launcher screen in Android app only once. Then if the user is on the second screen, if he presses back button, I want app to close. What's wrong in this code? The first screen shows again, what mustn't be.

public class MainActivity extends Activity {

    private boolean firstscreenshown=false; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (firstscreenshown==true) finish();
        firstscreenshown=true;

or

public class MainActivity extends Activity {

    private boolean firstscreenshown; 

    public MainActivity() {
        this.firstscreenshown = false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (firstscreenshown==true) finish();
        firstscreenshown=true;
4

4 に答える 4

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 に答える