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在实际项目中的应用案例,通过属性可以为代码添加元数据,从而实现各种功能和特性。