简体   繁体   English

与C#中的'as'运算符等效的Objective-C

[英]Objective-C equivalent for 'as' operator in C#

Does Objective-C have a cast operator similar to 'as' operator in C# or the recommended way is to use isKindOfClass method to test the object and if yes cast the object to desired class? Objective-C是否具有与C#中的'as'运算符相似的转换运算符,或者推荐的方法是使用isKindOfClass方法测试对象,如果是,则将该对象转换为所需的类?
In C# I do this: 在C#中,我这样做:

Class1 o1 = obj as Class1;
if (o1 != null)
{
    // ...
}

In Objective-C should I go with this: 在Objective-C中,我应该这样做:

if ([obj isKindOfClass:[Class1 class]]) {
    Class1* o1 = (Class1*)obj;
    // ...
}

You are right, isKindOfClass is the correct Objective-C way to check if an object is an instance of a given class or an instance of a subclass. 没错, isKindOfClass是检查对象是给定类的实例还是子类的实例的正确的Objective-C方法。

But have a look at the answers of 但看看答案

for various neat macros, categories and even a C++ template to provide a syntax that mimics the C++ dynamic_cast or the C# as operator. 用于各种整洁的宏,类别,甚至是C ++模板,以提供模仿C ++ dynamic_cast或C# as运算符的语法。

class A { }
class B : A { }

A a = new A();
if(a.GetType() == typeof(A)) // returns true
{
}

A b = new B();
if(b.GetType() == typeof(A)) // returns false
{
}

or 要么

test ts = new test();
            object ob = ts;

            if (typeof(test) == ob.GetType())
               {
                   return true;
               }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM