c#特性学习(1)

时间:2023-03-08 23:26:06
c#特性学习(1)

  C#中的特性我认为可以理解为Java中的注解,见名知意,就是描述这个类或是属性的一个信息,是一个语法糖.原理运用的是反射,下面我来演示一下它的原理.其中引用了软谋的代码.

  举一个栗子.我们在做codefirst的时候有时候类名和表名我们不想要一样的,那么就可以利用特性来指定表名.

  先来一个UserModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 特性
{
public class User
{
public int Id { get; set; }
public string Account
{
set;
get;
}
/// <summary>
/// 密码
/// </summary>
public string Password
{
set;
get;
}
/// <summary>
/// EMaill
/// </summary>
public string Email
{
set;
get;
}
/// <summary>
/// 手提
/// </summary>
public string Mobile
{
set;
get;
}
/// <summary>
/// 企业ID
/// </summary>
public int? CompanyId
{
set;
get;
}
/// <summary>
/// 企业名称
/// </summary>
public string CompanyName
{
set;
get;
}
/// <summary>
/// 用户状态 0正常 1冻结 2删除
/// </summary>
public int? State
{
set;
get;
}
/// <summary>
/// 用户类型 1 普通用户 2管理员 4超级管理员
/// </summary>
public int? UserType
{
set;
get;
}
/// <summary>
/// 最后一次登陆时间
/// </summary>
public DateTime? LastLoginTime
{
set;
get;
} /// <summary>
/// 最后一次修改人
/// </summary>
public int? LastModifierId
{
set;
get;
}
/// <summary>
/// 最后一次修改时间
/// </summary>
public DateTime? LastModifyTime
{
set;
get;
}
}
}

UserModel

  再来一个自定义特性类,使用特性需要继承Attribute抽象类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 特性
{
public class TableAttribute:Attribute
{
private string _TableName = null; public TableAttribute(string tableName)
{
this._TableName = tableName;
} public string GetTableName()
{
return this._TableName;
}
}
}

TableAttribute

  对UserModel添加扩展方法,这里运用反射,调用GetCustomAttributes方法获取自定义特性的数组

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 特性
{
public static class Extend
{
public static string GetTableName<T>(this T t) where T : new()
{
Type type = t.GetType();
object[] oAttributeList = type.GetCustomAttributes(true);
foreach (var item in oAttributeList)
{
if (item is TableAttribute)
{
TableAttribute attribute = item as TableAttribute;
return attribute.GetTableName();
}
} return type.Name;
}
}
}

Extend

  对UserModel添加特性,可以省略Attribute后缀

c#特性学习(1)

  调用方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 特性
{
class Program
{
static void Main(string[] args)
{
User user = new User
{
Id =
}; string name = user.GetTableName<User>(); Console.WriteLine(name);
Console.ReadKey();
}
}
}

查看结果

c#特性学习(1)