如何告诉编译器只有 属性 存在时才被访问?
How to tell the compiler that a property is only accessed if it exists?
我可以使用 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 子句。
有解决办法吗?
您必须包含对 Microsoft.CSharp
的引用才能使其正常工作,并且您需要 using System.Reflection;
。这是我的解决方案:
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 帮助我解决这个问题。
我可以使用 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 子句。
有解决办法吗?
您必须包含对 Microsoft.CSharp
的引用才能使其正常工作,并且您需要 using System.Reflection;
。这是我的解决方案:
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 帮助我解决这个问题。