开发者

Trouble with type casting in c#

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?


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;


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.


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


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();
}


You can also do this:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜