2011-07-05 32 views
0

對於C#中的跨平臺庫,我希望爲了可擴展性的目的而具有一組標記爲保護的方法。這些方法後來被反射訪問,使用元編程與屬性使用#if和#define指定訪問者

然而,在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() 
     { 
     } 
    } 
} 

回答

3

你可以這樣做:

[MyAttribute] 
#if WINDOWS_PHONE 
internal 
#else 
protected 
#endif 
void MyMethod() 
{   
} 

但是你最好不要讓他們internalprotected internal

+0

嗯,如果該成員被標記爲受保護的,那麼我會得到一個安全異常。所以除非「受保護的內部」並不意味着它受到保護,否則我不確定它會有什麼區別。再次,將它們標記爲內部意味着其他程序集沒有可擴展性(這違背了整個想法) –

+0

'protected internal'意味着它受到保護或者是內部的。試一試。 –

+0

是的,這是OR ... –

1

我不認爲你可以使用的語言結構的替代,你應該能做什麼常數是:

namespace Example 
{ 
    public class MyTestClass 
    { 
     [MyAttribute] 
    #if WINDOWS_PHONE 
     internal void MyMethod() 
    #else 
     protected void MyMethod() 
    #endif 
     { 
     } 
    } 
} 
0

我相信這將工作:

namespace Example 
{ 
    public class MyTestClass 
    { 
     [MyAttribute]  
#if WINDOWS_PHONE 
     internal void MyMethod() 
#else 
     protected void MyMethod() 
#endif 
     { 
     } 
    } 
} 
0

你不能使用#define這種方式。它不像C.根據MSDN

#define讓你定義一個符號。當您將該符號用作傳遞給#if指令的表達式時,表達式將計算爲true。

羅伯特皮特的答案看起來像一個很好的解決方法。