检查AppDelegate中的方法/属性是否存在

时间:2015-11-23 11:38:55

标签: c# ios reflection xamarin xamarin.ios

我试着找出AppDelegate是否包含某个属性/方法。为此,我找到了Check if a property exist in a classHow to check whether an object has certain method/property?,但AppDelegate似乎有所不同。

以下内容无法编译

if(AppDelegate.HasMethod("SomeMethod"))

,因为

  

AppDelegate不包含HasMethod的定义。

我也尝试了其他变体,但我没有设法成功检查方法/属性是否存在。此外respondsToSelector似乎不适用于此。 GetType()也无法使用AppDelegate

检查AppDelegate中的属性/方法是否存在的正确方法是什么?

修改

似乎我需要一个AppDelegate的实例来处理它。对我而言,问题是如何确保此实例可用?例如。如果未实施则抛出异常?

以下是您可以做的事情:

的AppDelegate

public static new AppDelegate Self { get; private set; }

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
    AppDelegate.Self = this;

    return true;
}

[Export ("YourMethod:")]
public void YourMethod (bool setVisible){
    // do something
}

某些课程

if(AppDelegate.Self.RespondsToSelector(new Selector("YourMethod:")))
{
    AppDelegate.Self.YourMethod (true);
}

您不需要使用respondsToSelector,如果您拥有实例,您也可以使用其他C#/ .NET方法(来自链接线程的HasMethodHasPropertyAppDelegate。对我而言,问题是如何确保在Self中实施AppDelegate

是的,编译器会为我检查,但我想只在实现时才执行该方法。它不应该是实现它的必要条件。它应该没有YourMethod

2 个答案:

答案 0 :(得分:1)

更新回答

我知道这仍然是Obj-C,但你应该能够轻松获得C#等价物。

#import "AppDelegate.h"

SEL selector = NSSelectorFromString(@"possibleMethod");
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
if([appDelegate respondsToSelector:selector]){
    [appDelegate selector];
}
祝你好运

首先,

#import "AppDelegate.h"

您可以使用@try块尝试以下方法,尝试测试选择器。

    BOOL methodExists = YES;
    SEL yourVariable = NSSelectorFromString(@"possibleMethod");
    AppDelegate * ad = [[AppDelegate alloc]init];

    @try {
        [ad performSelector:yourVariable withObject:nil afterDelay:0.0];
    }
    @catch (NSException *exception) {
        methodExists = NO;
    }
    @finally {

        if (methodExists) {
            //Call method from selector
        }

    }

答案 1 :(得分:1)

最后我找到了解决方案。首先,您需要两种扩展方法:

public static class GeneralExtensions
{
    public static bool HasProperty(this object obj, string propertyName)
    {
        return obj.GetType().GetProperty(propertyName) != null;
    }

    public static bool HasMethod(this object objectToCheck, string methodName)
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    } 
}

检查您使用的方法

if (UIApplication.SharedApplication.Delegate.HasMethod("YourMethod")){
    // do something
}

检查您使用的财产

if (UIApplication.SharedApplication.Delegate.HasProperty("Instance"))
    // do something
}

这个想法来自this thread

但这不是故事的结局。我的最终方法可以找到here

相关问题