在C#中,可以使用自定义属性(Attribute)来实现数据约束。下面是一个简单的示例,展示了如何创建一个自定义属性来限制字符串长度:
System.Attribute
:using System;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class StringLengthAttribute : Attribute
{
private readonly int _maxLength;
public StringLengthAttribute(int maxLength)
{
_maxLength = maxLength;
}
public int MaxLength => _maxLength;
}
public class User
{
[StringLength(10)]
public string Username { get; set; }
[StringLength(50)]
public string Email { get; set; }
}
using System.Reflection;
public static class Validator
{
public static bool IsValid(object obj)
{
var type = obj.GetType();
var properties = type.GetProperties();
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes<StringLengthAttribute>();
foreach (var attribute in attributes)
{
var value = property.GetValue(obj) as string;
if (value != null && value.Length > attribute.MaxLength)
{
return false;
}
}
}
return true;
}
}
Validator.IsValid()
方法来验证对象是否满足约束条件:var user = new User { Username = "JohnDoe", Email = "john.doe@example.com" };
if (Validator.IsValid(user))
{
Console.WriteLine("User data is valid.");
}
else
{
Console.WriteLine("User data is invalid.");
}
这个示例仅限于字符串长度约束,但你可以根据需要创建更多的自定义属性来实现其他类型的约束。