如何告诉编译器一个属性只有在它存在时才被访问? [英] How to tell the compiler that a property is only accessed if it exists?

查看:50
本文介绍了如何告诉编译器一个属性只有在它存在时才被访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 HasProperty 检查属性是否存在.仅当属性存在时才应执行方法.

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
}

事情是这样的:首先,我检查属性是否存在.如果是,我执行我的方法.所以通常代码永远不会执行(除非属性存在),但编译器无法区分这一点.它只检查属性是否存在,不考虑 if 子句.

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?

推荐答案

您必须包含对 Microsoft.CSharp 的引用才能使其正常工作,并且您需要 使用 System.Reflection;.这是我的解决方案:

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 });
}

这是HasMethod背后的代码:

Here is the code behind HasMethod:

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

感谢 DavidG 帮助我解决这个问题.

Thanks to DavidG for helping me out with this.

这篇关于如何告诉编译器一个属性只有在它存在时才被访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆