首页 > 解决方案 > Applying a custom identifier on variables within a class

问题描述

As part of a random data generator, I have a class which contains various string parameters, such as:

class Container
{
    string FirstName {get; set;}
    string LastName {get; set;}
    string ContactNo {get; set;}
}

Note that I require ContactNo as a string to retain the leading 0.

I then loop through these parameters and generate a random value programmatically, however I need to be able to determine when to generate a random word (for FirstName & LastName) or number (for ContactNumber).

BindingFlags flags = BindingFlags.Public |
    BindingFlags.NonPublic |
    BindingFlags.Instance |
    BindingFlags.Static;

foreach (FieldInfo field in typeof(Container).GetFields(flags))
{
    // Check custom identifier to see whether a random word or number is required.
}

可以在变量名称中包含某种标识符,表明是否需要数字或单词,但是我执行类似的任务将标头应用于输出 csv 并为此使用变量名称,但我真的不想拥有包含此信息的标头。我想总是可以采用这种方法,但删除标识符,但这似乎有点混乱。

谁能指出我可以实现这一目标的另一种方式?

编辑

感谢 ChrisDunaway 强调您需要查看属性而不是字段,例如:

BindingFlags flags = BindingFlags.Public |
    BindingFlags.NonPublic |
    BindingFlags.Instance |
    BindingFlags.Static;

foreach (Propertyinfo field in typeof(Container).GetProperties(flags))
{
    // Check custom identifier to see whether a random word or number is required.
}

标签: c#

解决方案


你应该使用属性。这可能会帮助您:

class Container
{
    string FirstName { get; set; }
    string LastName { get; set; }
    [IsNumber]
    string ContactNo { get; set; }
}

public class IsNumber : Attribute { }

public static void test()
    {
        var flags = BindingFlags.Public |
                   BindingFlags.NonPublic |
                   BindingFlags.Instance |
                   BindingFlags.Static;

        foreach (PropertyInfo property in typeof(Container).GetProperties(flags))
        {
            if (property.GetCustomAttributes(typeof(IsNumber), true).Length > 0)
            {
                MessageBox.Show("property " + property.Name + " is number");
                // this is a number field
            }
            // Check custom identifier to see whether a random word or number is required.
        }
    }

推荐阅读