c# 属性类(特性)

前言

c# 属性类也称做特性。这是一篇垫文,为后面的过滤器和其他特性类的东西做铺垫。

正文

看一段代码:

static void Main(string[] args)
{
	Attribitefunc1.printMesssage("卡特林");
	Console.ReadLine();
}

/// <summary>
/// Attribitefunc1 is class that provite a print method
/// </summary>
public class Attribitefunc1{
	[Conditional("release")]
	public static void printMesssage(string msg)
	{
		Console.WriteLine("输出数据:"+ msg);
	}
}

然后发现不会有任何输出;

然后我加上#define release;

结果:

那么我们明白原来这个是否执行是根据是否预处理来判断的,这使得我们程序变得很方便。

再举一个例子:

我们在开发一个项目中,如果我们废弃了代码,我们是不会去立即删除的,因为需要回顾历史。

static void Main(string[] args)
{
	Attribitefunc1.printMesssage("卡特林");
	Console.ReadLine();
}

/// <summary>
/// Attribitefunc1 is class that provite a print method
/// </summary>
public class Attribitefunc1{
	[Obsolete("this is old",true)]
	public static void printMesssage(string msg)
	{
		Console.WriteLine("输出数据:"+ msg);
	}
}

这时候显示的是:

当然有时候我们是不会让他报错的,只需要警告。

[Obsolete("this is old",false)]

好了,既然属性这么好用不如我们就来自定义吧!

就用验证来举例子吧!

[AttributeUsage(AttributeTargets.Property,AllowMultiple =true,Inherited =true)]
public abstract class BaseAttribute:Attribute
{
	public virtual string error { get; set; }

	public abstract bool Validate(object value);
}

要实现属性就要继承属性!

在属性类上我们可以加一些特性,AttributeUsage。

比如说:

AttributeTargets 表示的是作用于什么位置,你可以限制是类或者属性等等。

AllowMultiple 是否可以有多个属性,因为验证有验证是否为空、验证是长度等等,需要为true。

Inherited 这个是否可继承,一般是可继承的。

下面以不为空来举例:

public class RequiredAttribute : BaseAttribute
{
	public override string error {
		get {
			if (base.error != null)
			{
				return base.error;
			}
			return "属性不能为空";
		}
		set { base.error = value;
		}
	}
	public override bool Validate(object value)
	{
		return !(value == null);
	}
}

上面我继承了BaseAttribute,实现BaseAttribute里面的方法和属性。

下面我又一个student类:

public class Student
{
	private string name;
	[Required]
	public string Name { get => name; set => name = value; }
}

那么我给Name值不能为空的属性。

同样我们要去实现验证过程,为了解耦,需要加一个helper类;

public class ValidateHelper
{
	public static string Validate<T>(T t)
	{
		Type type = t.GetType();
		PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
		foreach (PropertyInfo propertyInfo in propertyInfos)
		{
			if (propertyInfo.IsDefined(typeof(BaseAttribute)))
			{
				foreach (BaseAttribute attribute in propertyInfo.GetCustomAttributes(typeof(BaseAttribute)))
				{
					if (!attribute.Validate(propertyInfo.GetValue(t, null)))
					{
						return attribute.error;
					}
				}
			}
		}
		return null;
	}
}

上面的原理非常简单,就是遍历一个泛型里面的属性,找到里面的特性进行判断。

我们需要书写的判断过程如下:

Student student = new Student();
var errormessage=ValidateHelper.Validate(student);
Console.WriteLine(errormessage);
Console.ReadKey();

得到的结果:

介绍完毕!

猜你喜欢

转载自www.cnblogs.com/aoximin/p/12801337.html