Trouble with type casting in c#

时光毁灭记忆、已成空白 提交于 2019-12-11 18:06:56

问题


I have 2 classes:

class A {
    public void A_1(Object b) {
        ...
        Type t = b.GetType();
        (t.FullName)b.B_1(); //It doesn`t work! Error in cast
    }
    ....
}

class B {
    public void B_1() {
        ...
    }
    ....
}

A a = new A();
B b = new B();
a.A1(b);

How to cast object correctly?


回答1:


If you want to cast an object of any type to an object of another type, you do this:

// Will Throw an exception at runtime if it cant be cast.
B newObject = (B)oldObject; 

// Will return null at runtime if the object cannot be cast
B newObject = oldObject as B; 

// If in a generic method, convert based on the generic type parameter regardless of condition - will throw an exception at runtime if it cant be cast
B newObject = (T)Convert.ChangeType(oldObject, typeof(T))

Your syntax is off; you don't convert from the fullname to the object, you simply convert from the type symbol.

double x = (double)40;

ClassB anotherInstance = (ClassB)someOtherInstance;



回答2:


What you're trying to do is basically:

Foo myFoo = ("Foo")myObject;

That definitely will not work in C#. When you cast in C#, the compiler emits code that does the cast, it needs to know what it's casting from and to, in order to write that code. A string does not help the compiler out here.

As others have pointed out, what you want to do doesn't seem like you really need to (unless this is just a contrived example). If you really want to do this, you'll need to work with a more dynamic language than C#, or find a C# friendly way of accomplishing this.




回答3:


Are you sure you didn't mean to do (B)b.B_1()?




回答4:


C# has a static type-system, i.e. all types must be known at compile-time (modulo reflection). So, casting to a type that is only known at run-time makes no sense. Specify the type explicitly:

public void A_1(object obj)
{
    ...
    B b = (B)obj;
    b.B_1();
    // or
    ((B)obj).B_1();
}



回答5:


You can also do this:

class A {
    public void A_1(Object b) {
        ...
        if (b is B)
        {
             ((B)b).B_1();
        }
    }
    ....
}



回答6:


Type.FullName is just a string; it's not a type. Use this instead: ((B)b).B_1(); Also, using GetType() is a way to get the type of an object dynamically, but casting is only possible or useful when the target type is known at compile time (not dynamic at all). In order to cast, simply refer to the type directly in a pair of parentheses. Don't attempt to obtain or use an object of type Type.



来源:https://stackoverflow.com/questions/5871702/trouble-with-type-casting-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!