C ++ / CLI-问题:有一个等价于C#“is”关键字或者我必须使用反射吗? [英] C++/CLI-Question: Is there an equivalent to the C# "is" keyword or do I have to use reflection?

查看:249
本文介绍了C ++ / CLI-问题:有一个等价于C#“is”关键字或者我必须使用反射吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过MSDN上的某个地方,相当于C#的is关键字将是dynamic_cast,但这不是真的相等:它不适用于值类型或通用参数。例如在C#中我可以写:

  void MyGenericFunction< T>()
{
object x = ...
if(x is T)
...;
}



如果我尝试等效C ++ / CLI:

  generic< class T> 
void MyGenericFunction()
{
object x = ...
if(dynamic_cast< T>(x))
...;
}

我得到一个编译器错误错误C2682:不能使用'dynamic_cast'从'System :: Object ^'到'T'。



我唯一能想到的是使用反射:

  if(T :: typeid-> IsAssignableFrom(obj-> GetType()))

有更简单的方法吗?

解决方案

使用 safe_cast 在本地C ++中使用 dynamic_cast 并捕获System :: InvalidCastException。就兼容类型而言,询问是否可以转换类型的语义可以检查比检查身份更广泛的类型。你实际上可能想要增加IsAssignableFrom的灵活性。



我不认为有效的等效于旧的 dynamic_cast 成语我们习惯,当然没有紧凑。


I've read somewhere on MSDN that the equivalent to C#'s "is" keyword would be dynamic_cast, but that's not really equivalent: It doesn't work with value types or with generic parameters. For example in C# I can write:

void MyGenericFunction<T>()
{
    object x = ...
    if (x is T)
        ...;
}

If I try the "equivalent" C++/CLI:

generic<class T>
void MyGenericFunction()
{
    object x = ...
    if (dynamic_cast<T>(x))
       ...;
}

I get a compiler error "error C2682: cannot use 'dynamic_cast' to convert from 'System::Object ^' to 'T'".

The only thing I can think of is to use reflection:

if (T::typeid->IsAssignableFrom(obj->GetType()))

Is there a simpler way to do this?

解决方案

You can use safe_cast where you would use dynamic_cast in native C++ and trap the System::InvalidCastException. In terms of compatible types the semantics of asking if you can convert types could pick up a broader range of types than checking identity. You may actually want the added flexibility of IsAssignableFrom.

I don't think there's an efficient equivalent to the good old dynamic_cast idiom we're used to, certainly nothing as compact.

这篇关于C ++ / CLI-问题:有一个等价于C#“is”关键字或者我必须使用反射吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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