如何在C#中从其中访问类的属性

时间:2013-02-28 17:16:33

标签: c#

我有这个类的这些属性,我想知道如何从类中访问它们。 ServedClassName是一个自定义属性,这是我实际尝试访问的属性。

[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());

1 个答案:

答案 0 :(得分:6)

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

将为您提供类的ServedClassNameAttribute类型的自定义属性列表。然后,您可以像这样遍历属性实例:

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