C++到C#的"As"?

c++ to c#'s "As"?

本文关键字:As C++      更新时间:2023-10-16

如何将结构体强制转换为其基类型之一?

在c#中,你可以像Entity as Monster一样使用关键字"as"。我如何在c++中做到这一点?

这是我的结构:

struct Entity
{
    USHORT X;
    USHORT Y;
    UINT Serial;
    USHORT SpriteID;
};
struct Monster : Entity
{
    UINT UNKNOWN;
    BYTE Direction;
    USHORT Type;
};
struct Item : Entity
{
    BYTE UNKNOWN1;
    USHORT UNKNWON2;
};
struct NPC : Entity
{
    UINT UNKNOWN1;
    BYTE Direction;
    BYTE UNKNOWN2;
    BYTE NameLength;;   
    byte Name[];
};

在c++中,这种可能性只存在于指向多态类型对象的指针(即至少具有一个虚函数的类型)。你可以用dynamic_cast<PtrType>来做。

下面是一个完整的例子(也在ideone上):

#include <iostream>
using namespace std;
struct A {virtual void foo(){}};
struct B {virtual void foo(){}};
int main() {
    A *a = new A();     
    B *b = new B();
    A *aPtr1 = dynamic_cast<A*>(b);
    cout << (aPtr1 == 0) << endl; // Prints 1
    A *aPtr2 = dynamic_cast<A*>(a);
    cout << (aPtr2 == 0) << endl; // Prints 0
    delete a;
    delete b;
    return 0;
}

第一个dynamic_cast失败,因为b指向的对象类型与A*不兼容;第二个dynamic_cast成功

看看c++类型强制转换操作符:

http://www.cplusplus.com/doc/tutorial/typecasting/

Entity e;
Monster m = static_cast<Monster>(e);

如果实体至少有一个虚方法,你可以这样做:

Monster * m = dynamic_cast<Monster*>(&e); // m != null if cast succeed

注意c#的"as"不能在struct上工作。在这种情况下,你必须在c#中强制转换对象,这相当于c++中的static_cast

如果转换无效,程序将无法编译。

相关文章: