递归访问类的属性

发布于 2024-08-23 07:35:58 字数 1001 浏览 5 评论 0原文

以此示例类为例:

    [AttributeUsage(AttributeTargets.All, AllowMultiple=true)]
public class BugFixAttribute : System.Attribute
{
    public int BugId { get; private set; }
    public string Programmer { get; private set; }
    public DateTime Date { get; private set; }
    public string Comments { get; set; }
    public string RefersTo { get; set; }

    public BugFixAttribute(int bugId = 0, string programmer = "")
    {
        this.BugId = bugId;
        this.Programmer = programmer;
        Date = DateTime.Now;
    }
}

我想通过属性来回避使用:

object[] attr = info.GetCustomAttributes(typeof(BugFixAttribute), false);
foreach (object attribute in attr)
{
    BugFixAttribute bfa = (BugFixAttribute) attribute;
    Debug.WriteLine(string.Format("\nBugId: {0}", bfa.BugId));
    Debug.WriteLine(string.Format("Programmer: {0}", bfa.Programmer));
    //...
}

因为我需要做的是将这些打印到文件中。那么,我如何递归访问这些属性,而不是通过所有属性执行 Debug.WriteLine() ,有没有办法或者我必须把它写出来。

Take this sample class as an example:

    [AttributeUsage(AttributeTargets.All, AllowMultiple=true)]
public class BugFixAttribute : System.Attribute
{
    public int BugId { get; private set; }
    public string Programmer { get; private set; }
    public DateTime Date { get; private set; }
    public string Comments { get; set; }
    public string RefersTo { get; set; }

    public BugFixAttribute(int bugId = 0, string programmer = "")
    {
        this.BugId = bugId;
        this.Programmer = programmer;
        Date = DateTime.Now;
    }
}

And I want to recuse through the properties to use like:

object[] attr = info.GetCustomAttributes(typeof(BugFixAttribute), false);
foreach (object attribute in attr)
{
    BugFixAttribute bfa = (BugFixAttribute) attribute;
    Debug.WriteLine(string.Format("\nBugId: {0}", bfa.BugId));
    Debug.WriteLine(string.Format("Programmer: {0}", bfa.Programmer));
    //...
}

Because what I need to do is to print these to a file. So how can I recurse through the properties instead of doing the Debug.WriteLine() through all of them, is there a way or do I have to write it out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

静谧幽蓝 2024-08-30 07:35:58

我建议这对于属性来说可能不是一个很好的用途,因为它混淆了附加到代码的元。如果您想标准化一种获取有关错误修复的此类信息的方法,我建议您使用 XML 注释标签,然后为您的项目打开 XML 注释,并使用它。

语法示例:

/// <summary>This Method Does Something</summary>
/// <BugFix BugId="1234" Programmer="Bob" Date="2/1/2010">Fix Comments</BugFix>
public void MyMethod()
{
    // Do Something
}

I would suggest that this is probably not a great use for Attributes, as it muddies up the meta attached to the code. If you want to standardize a way to get at this sort of information regarding bug fixes, I would suggest coming up with an XML Comment Tag, and then turning on XML Comments for your project, and using that instead.

Example Syntax:

/// <summary>This Method Does Something</summary>
/// <BugFix BugId="1234" Programmer="Bob" Date="2/1/2010">Fix Comments</BugFix>
public void MyMethod()
{
    // Do Something
}
难如初 2024-08-30 07:35:58

是的,如果您使用反射:

Type t = bfa.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach(var prop in properties)
{
    Debug.WriteLine(string.Format("{0}: {1}", prop.Name,prop.GetValue(bfa,null)));
}

这将打印 bfa 中所有公共属性的名称和值。您可以检查 PropertyInfo 上的 CanRead 属性来检查它是否可以读取(即它是否声明了 getter)。如果其中一个属性是只读的或已索引,则该示例将失败 - 如果发生这种情况,您需要在代码中检查它。

Yes, if you use reflection:

Type t = bfa.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach(var prop in properties)
{
    Debug.WriteLine(string.Format("{0}: {1}", prop.Name,prop.GetValue(bfa,null)));
}

This will print the name and value of all public properties in bfa. You can check the CanRead property on a PropertyInfo to check if it can be read (ie. if it declares a getter). The example will fail if one of the properties are read-only or is indexed - if this can occur, you need to check for it in the code.

甜味拾荒者 2024-08-30 07:35:58

我喜欢 Linq 的这种功能

var props = from b in info.GetCustomAttributes(typeof(BugFixAttribute), false)
            from p in b.GetType().GetProperties()
            select new { 
                   Name = p.Name,
                   Value = p.GetValue(p.GetValue(b, null))
                   };

foreach(var prop in props)
{
    Debug.WriteLine(string.Format("{0}: {1}", prop.Name, prop.Value));
}

I love Linq for this kind of thing

var props = from b in info.GetCustomAttributes(typeof(BugFixAttribute), false)
            from p in b.GetType().GetProperties()
            select new { 
                   Name = p.Name,
                   Value = p.GetValue(p.GetValue(b, null))
                   };

foreach(var prop in props)
{
    Debug.WriteLine(string.Format("{0}: {1}", prop.Name, prop.Value));
}
早乙女 2024-08-30 07:35:58

如果我正确地阅读了问题,您正在寻找一种更简单的方法来写出班级信息,对吗?你有两个选择:

  1. 反射,对于一个高度通用的解决方案,它可能会输出太多信息(假设这是 java - 或 .NET,我被告知它们非常相同......)
  2. 定义 toString( ) 方法,并调用 Debug.WriteLine(bfa)

解决方案 1 可能是way过度杀伤力。您可能会得到您不想要的内容的输出,并且您将无法获得私有值。

解决方案2是简单的方法。

public class BugFixAttribute : System.Attribute
{
 ...

 public String toString(){
   return string.Format("\nBugId: {0}\nProgrammer: {1}", this.BugId, this.Programmer));
 }
}

If I read the question correctly, you're looking for a simpler way to write out the class information, right? You've got two options:

  1. reflection, for a highly generic solution that will prolly output way too much information (assuming this is java - or .NET which I've been told is very much the same...)
  2. define the toString() method, and call Debug.WriteLine(bfa)

Solution 1 is probably way overkill. You'll probably get output for stuff you don't want, and you'll not be able to get private values.

Solution 2 is the simple way.

public class BugFixAttribute : System.Attribute
{
 ...

 public String toString(){
   return string.Format("\nBugId: {0}\nProgrammer: {1}", this.BugId, this.Programmer));
 }
}
泪是无色的血 2024-08-30 07:35:58
foreach (var (BugFixAttribute)attribute in attr)
{
    foreach(PropertyInfo prop in attribute.GetType().GetProperties())
    {
        Debug.WriteLine(string.Format("{0}: {1}", prop.name,prop.GetValue(attribute,null));
    }
}
foreach (var (BugFixAttribute)attribute in attr)
{
    foreach(PropertyInfo prop in attribute.GetType().GetProperties())
    {
        Debug.WriteLine(string.Format("{0}: {1}", prop.name,prop.GetValue(attribute,null));
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文