在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.");
}
這個示例僅限于字符串長度約束,但你可以根據需要創建更多的自定義屬性來實現其他類型的約束。