问题
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