public class Logger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
public class LogAttribute : Attribute
{
public string Message { get; }
public LogAttribute(string message)
{
Message = message;
}
}
public class MyClass
{
private Logger _logger = new Logger();
[Log("Method1 is called")]
public void Method1()
{
_logger.Log("Method1 is executing");
}
[Log("Method2 is called")]
public void Method2()
{
_logger.Log("Method2 is executing");
}
}
public class User
{
[Required]
public string Username { get; set; }
[EmailAddress]
public string Email { get; set; }
}
public class UserRepository
{
public void SaveUser(User user)
{
// 使用反射獲取User類的屬性,并根據屬性上的ValidationAttribute進行驗證
}
}
public interface IMyInterface
{
[Description("This method does something")]
void DoSomething();
[Description("This property holds some value")]
string SomeValue { get; set; }
}
public class InterfaceDescriptionGenerator
{
public string GenerateDescription(Type type)
{
// 使用反射獲取接口的方法、類或屬性,并根據屬性生成描述文檔
}
}
這些是C# attributes在實際項目中的應用案例,通過屬性可以為代碼添加元數據,從而實現各種功能和特性。