在C#中进行类型转换有问题 [英] Trouble with type casting in c#

查看:56
本文介绍了在C#中进行类型转换有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个课程:

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

如何正确投射对象?

推荐答案

您要尝试的操作基本上是:

What you're trying to do is basically:

Foo myFoo = ("Foo")myObject;

那绝对不会在C#中起作用.使用C#进行强制转换时,编译器会发出进行强制转换的代码,为了编写该代码,编译器需要知道它要进行的转换.字符串对此处的编译器无济于事.

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.

正如其他人指出的那样,您想要做的事情似乎并不是您真正需要的(除非这只是一个人为的示例).如果您确实想这样做,则需要使用比C#更动态的语言,或者找到一种C#友好的方式来实现这一目标.

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.

这篇关于在C#中进行类型转换有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆