gpt4 book ai didi

c# - 在类中的变量上应用自定义标识符

转载 作者:太空宇宙 更新时间:2023-11-03 22:43:56 24 4
gpt4 key购买 nike

作为随机数据生成器的一部分,我有一个包含各种字符串参数的类,例如:

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

请注意,我需要 ContactNo 作为字符串以保留前导 0。

然后我遍历这些参数并以编程方式生成一个随机值,但是我需要能够确定何时生成随机词(对于 FirstName 和 LastName)或数字(对于 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 并为此使用变量名称,但我真的不想让 header 包含此信息。我想总是可以采用这种方法,但删除标识符,但这似乎有点困惑。

谁能指出我实现此目标的另一种方法?

编辑

感谢 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.
}

最佳答案

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

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.
}
}

关于c# - 在类中的变量上应用自定义标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50877705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com