c# - 检查属性
问题描述
我有一个方法,我想在它运行之前检查每个具有特定属性的类和接口为它们运行该方法,而不是为其他类运行。我该如何设置这个条件?
解决方案
您可以使用这种方式,首先使用您的特定属性创建一个类(我使用SerializableAttribute
):
[Serializable]
public class Sample
{
public string Name { get; set; }
}
如果类具有特定属性,则创建方法来做某事:
public void SampleMethod<T>() where T : class
{
//skip if class has not your attribute
if (typeof(T).GetCustomAttribute(typeof(SerializableAttribute)) == null)
return;
//do other stuff
}
调用方法如下:
SampleMethod<Sample>();
推荐阅读
- html - 响应式设计 全选
- nginx - Nginx 在 nginx.conf 中更改访问日志格式没有效果
- python - 如何在深度学习中向现有分类器添加新类?
- batch-file - 为什么下面的批处理代码可能会退出?
- modelica - 使用先前模拟结果的结果值作为 Dymola 中下一次模拟的猜测值
- java - 如何在java中的client_server聊天中禁止客户端
- docker - 通过 Traefik 和 Docker 容器使用多个端口/主机
- javascript - 将字符串修剪到小数点后两位
- python - 尝试创建下拉菜单pygame,但卡住了
- java - 某些数字计数器