c# - 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.
}
解决方案
你应该使用属性。这可能会帮助您:
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.
}
}
推荐阅读
- java - 无法返回值
- python - 熊猫中几个数据帧的异步“read_csv” - 为什么它不更快
- node.js - 什么可能导致 localhost:4200 在路由调用之前添加?
- fortran - 了解 Fortran 如何初始化模块中定义的派生类型数组
- python - 如何在 Python 中进行调度作业以弹出列表中的元素?
- json - 如何使用抽象继承将 JSON 编码和解码为 TypeScript 模型?
- jasper-reports - 如何在 Jasper 报表中显示嵌套列表
- python - Keras Sequential 不提供输入形状
- error-handling - 本机 std::errc/errno 值和一些托管异常/错误代码之间的映射
- azure - 负载均衡器不允许流量返回