使用#if和#define指定访问器
本文关键字:访问 #define #if 使用 | 更新日期: 2023-09-27 18:01:14
对于C#中的跨平台库,出于可扩展性的目的,我希望有一组标记为protected的方法。这些方法稍后通过反射访问,使用属性为的元编程
然而,在Windows Phone 7上,不允许通过反射访问受保护的方法,相反,我希望将它们标记为内部。
所以我想知道的是,我是否可以在C#中做这样的事情,或者是否有更好的解决方法?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if WINDOWS_PHONE
#define ACCESSOR internal
#else
#define ACCESSOR protected
#endif
namespace Example
{
public class MyTestClass
{
[MyAttribute]
ACCESSOR void MyMethod()
{
}
}
}
您可以这样做:
[MyAttribute]
#if WINDOWS_PHONE
internal
#else
protected
#endif
void MyMethod()
{
}
但你最好把它们做成internal
或protected internal
。
我认为你不能用常量来代替语言结构,你应该能够做的是:
namespace Example
{
public class MyTestClass
{
[MyAttribute]
#if WINDOWS_PHONE
internal void MyMethod()
#else
protected void MyMethod()
#endif
{
}
}
}
我相信这会奏效:
namespace Example
{
public class MyTestClass
{
[MyAttribute]
#if WINDOWS_PHONE
internal void MyMethod()
#else
protected void MyMethod()
#endif
{
}
}
}
不能以这种方式使用#define
。它不像C。根据MSDN
#define
用于定义符号。当使用符号作为传递给#if指令的表达式时,该表达式的计算结果将为true。
罗伯特·皮特的回答看起来不错。