[英]C# string Formatting based on Model Attribute Annotation
我正在处理一个“.dat”文件创建项目,其中要求生成一个文件,其中包含所有字符串值的必要填充“零”或“空格”。
例如:我有一个如下所示的Class
,要求是在使用此 model 生成文件时,文件内容的长度应为 7 个字符,低于该长度的任何内容都应替换为"0" character
。
public class Header
{
// String length of 7, append "0" for leftover spaces.
public string RECORD_TYPE { get;set;};
}
考虑到上述要求,如果我将此字段的值设置为"ABC"
(即长度为 3 个字符),则在生成满足7 characters requirement
的文件时应将其转换为"ABC0000"
。
为此,我创建了一个自定义属性,如下所示:
public interface IFormatterAttribute
{
string Format(string toFormat);
}
[AttributeUsage(AttributeTargets.All)]
public class PaddedLengthAttribute : Attribute, IFormatterAttribute
{
private readonly int _length;
private readonly char _paddingChar;
private readonly PaddingDirection _paddingDirection;
public PaddedLengthAttribute(int length, char paddingChar = '0', PaddingDirection direction = PaddingDirection.Right)
{
_length = length;
_paddingChar = paddingChar;
_paddingDirection = direction;
}
public string Format(string toFormat)
{
return _paddingDirection switch
{
PaddingDirection.Left => toFormat.PadLeft(_length, _paddingChar),
PaddingDirection.Right => toFormat.PadRight(_length, _paddingChar),
_ => toFormat.PadRight(_length, _paddingChar),
};
}
public enum PaddingDirection
{
Left,
Right
}
}
因此,我可以使用下面的自定义属性来装饰 Field:
[PaddedLengthAttribute(7,'0')]
public class Header
{
// String length of 7, append "0" for leftover spaces.
public string RECORD_TYPE { get;set;};
}
我在这里需要帮助来理解为分配给它的每个属性动态调用PaddedLengthAttribute
class 的Format
方法的更好方法。
您可以使用 Reflection 遍历 Header class 的属性并检索它们的属性,如果属性具有 PaddedLengthAttribute,则可以使用它来格式化属性值。
这是一个例子:
public static class AttributeHelper
{
public static void ApplyPaddingAttributes(Header header)
{
var headerType = header.GetType();
var properties = headerType.GetProperties();
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes(typeof(PaddedLengthAttribute), false);
if (attributes.Length > 0)
{
var value = (string)property.GetValue(header);
var attribute = (PaddedLengthAttribute)attributes[0];
property.SetValue(header, attribute.Format(value));
}
}
}
}
你可以这样使用它:
var header = new Header() { RECORD_TYPE = "ABC" };
AttributeHelper.ApplyPaddingAttributes(header);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.