如何告诉编译器一个属性只有存在才被访问?
我可以使用HasProperty
来检查属性是否存在。 只有在属性存在的情况下,才能执行一个方法。
即使属性不存在,编译器如何成功编译? 例如
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 }
事情是这样的:首先,我检查是否存在这个动词。 如果是,我执行我的方法。 所以通常情况下代码是从不执行的(除了属性存在),但编译器无法区分这一点。 它只检查属性是否存在,不考虑if子句。
有这个解决scheme吗?
你必须包括对Microsoft.CSharp
的引用来获得这个工作,你需要using System.Reflection;
。 这是我的解决scheme:
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 }); }
这是HasMethod
背后的代码:
public static bool HasMethod(this object objectToCheck, string methodName) { var type = objectToCheck.GetType(); return type.GetMethod(methodName) != null; }
感谢DavidG帮助我解决这个问题。