2013-02-28 42 views
4

我有這個類的屬性,我想知道如何從類中訪問它們。 ServedClassName是一個自定義屬性,這是我實際嘗試訪問的屬性。如何在C#中訪問其中的類的屬性

[Guid("24889af6-e174-460b-ab52-7fb5a925926e")] 
[ServedClassName("ASCOM ProxyClient Telescope")] 
[ProgId("ASCOM.DeviceProxyClient.Telescope")] 
[ClassInterface(ClassInterfaceType.None)] 
public class Telescope : ReferenceCountedObjectBase, ITelescopeV3 

要訪問的ProgID,我用這個:Marshal.GenerateProgIdForType(this.GetType());

+2

反射不是一個選項? – allen 2013-02-28 17:18:00

+1

'TypeDescriptor.GetAttributes':http://msdn.microsoft.com/en-us/library/6w3a7b50%28v=vs.100%29.aspx 'Type.GetCustomAttributes':http://msdn.microsoft。 com/en-us/library/system.type.getcustomattributes.aspx – IAbstract 2013-02-28 17:18:07

回答

6
object [] attrs = GetType().GetCustomAttributes(typeof(ServedClassNameAttribute), true); 

會給你類型ServedClassNameAttribute對你的類的自定義屬性的列表。然後你可以通過像這樣的屬性實例:

foreach (ServedClassNameAttribute attr in attrs) 
{ 
    // Do something with attr 
} 
+0

不會使用'(typeof(...),false)'? Visual Studio說它沒有過載只是類型。或者我應該在那裏? – 2013-02-28 17:22:37

+0

我的不好,我會修復答案。如果從派生類也可能具有屬性的類派生,則要使用inherit = true。如果您只關心當前類是否具有屬性集而不是其基類,請使用inherit = false。 – 2013-02-28 17:25:07

+0

如果您只是使用'GetCustomAttributes(bool)'(http://msdn.microsoft.com/en-us/library/kff8s254.aspx),則返回當前'Type'實例的所有屬性。 – IAbstract 2013-02-28 18:16:07

相關問題