2017-02-26 87 views
0

我想查看ServiceKnownType屬性的源代碼,因爲我想知道如何編寫一些模擬其通用版本的東西。我想從實際的源代碼開始,並對其進行修改。這是ServiceKnownTypeAttribute的完整源代碼嗎?

我看了一下.NET源代碼庫,發現this link,但代碼非常稀疏,看起來並不像它包含了屬性的實現。請參閱下面的代碼。

我嘗試使用反編譯器,但生成的代碼看起來基本相同。沒有任何代碼,我不明白這個屬性是如何工作的!

任何人都知道我在哪裏可以找到實際的來源,假設它已經發布,當然。

這裏是從該鏈接的源代碼...

namespace System.ServiceModel 
{ 
    [AttributeUsage(ServiceModelAttributeTargets.ServiceContract | ServiceModelAttributeTargets.OperationContract, Inherited = true, AllowMultiple = true)] 
    public sealed class ServiceKnownTypeAttribute : Attribute 
    { 
     Type declaringType; 
     string methodName; 
     Type type; 

     private ServiceKnownTypeAttribute() 
     { 
      // Disallow default constructor 
     } 

     public ServiceKnownTypeAttribute(Type type) 
     { 
      this.type = type; 
     } 

     public ServiceKnownTypeAttribute(string methodName) 
     { 
      this.methodName = methodName; 
     } 

     public ServiceKnownTypeAttribute(string methodName, Type declaringType) 
     { 
      this.methodName = methodName; 
      this.declaringType = declaringType; 
     } 

     public Type DeclaringType 
     { 
      get { return declaringType; } 
     } 

     public string MethodName 
     { 
      get { return methodName; } 
     } 

     public Type Type 
     { 
      get { return type; } 
     } 
    } 
} 

回答

2

這看起來相當完整。像大多數屬性一樣,它只是將一些值(許多沒有值)與屬性本身的語義相關聯,因此反映在屬性所附屬的成員,類型和/或程序集上的代碼可以檢測到他們關心的屬性的存在,並且如果他們想要讀取屬性的任何屬性。

+0

謝謝,我期待更多的代碼比!所以,如果這就是全部,那麼我有點卡住了。作爲我原先思想的一種變體,假設我想寫一個屬性,它相當於將一個方法名稱傳遞給'ServiceKnownType' - 我該怎麼做?我想要在屬性代碼中指定特定類型,而不是傳遞方法。謝謝 –

+0

@AvrohomYisroel屬性不包含代碼,它們基本上是標誌。總是有*外部的東西*知道尋找這些標誌的存在/缺失並相應地改變它的行爲。例如。 P/Invoke編組人員知道尋找例如'MarshalAs'屬性,這個查找在其代碼中被硬編碼。因此,如果您不提供將尋找該屬性類型的* external *,那麼引入屬性來創建邏輯是毫無意義的。 – GSerg

+0

@Jon好的,謝謝你的解釋。看起來我比我明白的更深入了!因此,如果我想寫一個像ServiceKnownType這樣的屬性,但返回了一組特定的類型,就像使用允許指定一個返回類型集合的方法的重載一樣,我該怎麼做?如果我能做到這一點,我將能夠開始。再次感謝 –

0

事實上,你發佈了ServiceKnownTypeAttribute類的真實源代碼。屬性只是描述實體,它不包含任何邏輯。

0

你可能也想看看在Mono implementation

+0

感謝您的鏈接。我嘗試使用該代碼,但它失敗了。我將它複製到一個新的屬性MyServiceKnownType中,並改變了用法,但是我得到了與'SerializationException'相同的結果,就好像我根本沒有添加屬性一樣。任何想法出了什麼問題?我逐字複製了代碼。 –