How to tell the compiler that a property is only accessed if it exists?

坚强是说给别人听的谎言 提交于 2019-12-25 11:50:22

问题


I can use HasProperty to check if a property exists. Only if the property exists a method should be executed.

How can the compiler successfully compile even if the property doesn't exist? E.g.

if (UIApplication.SharedApplication.Delegate.HasProperty("Instance"))
{
    AppDelegate customAppDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
    customAppDelegate.Instance.SomeMethod(true); // can't be compiled because Instance doesn't exist
}

The thing is this: First, I check if the propery exists. If yes I execute my method. So normally the code is never executed (except the property exists), but the compiler isn't able to differentiate this. It only checks if the property exists and doesn't take the if clause into account.

Is there a solution for this?


回答1:


You have to include the reference to Microsoft.CSharp to get this working and you need using System.Reflection;. This is my solution:

if(UIApplication.SharedApplication.Delegate.HasMethod("SomeMethod"))
{
    MethodInfo someMethodInfo = UIApplication.SharedApplication.Delegate.GetType().GetMethod("SomeMethod");
    // calling SomeMethod with true as parameter on AppDelegate
    someMethodInfo.Invoke(UIApplication.SharedApplication.Delegate, new object[] { true });
}

Here is the code behind HasMethod:

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

Thanks to DavidG for helping me out with this.



来源:https://stackoverflow.com/questions/33872836/how-to-tell-the-compiler-that-a-property-is-only-accessed-if-it-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!