首页 > 解决方案 > 检查属性

问题描述

我有一个方法,我想在它运行之前检查每个具有特定属性的类和接口为它们运行该方法,而不是为其他类运行。我该如何设置这个条件?

标签: c#.net

解决方案


您可以使用这种方式,首先使用您的特定属性创建一个类(我使用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>();

推荐阅读