继承Attribute,自定义特性类
using System;
public class HttpApiKey : Attribute
{
public HttpApiKey(string _httpApi)
{
httpApi = _httpApi;
}
public string httpApi;
}
使用示例
public class HttpId
{
//示例,给id标记api
[HttpApiKey("Register")]
public const int registerId = 10001;
[HttpApiKey("Login")]
public const int loginId = 10002;
public static void GetHttpApi()
{
//反射获取字段
System.Reflection.FieldInfo[] fields = typeof(HttpId).GetFields();
System.Type attType = typeof(HttpApiKey);
for(int i = 0; i < fields.Length; i++)
{
if(fields[i].IsDefined(attType,false))
{
//获取id
int httpId = (int)fields[i].GetValue(null);
//获取api,读取字段的自定义Attribute
object attribute = fields[i].GetCustomAttributes(typeof(HttpApiKey),false)[0];
string httpApi = (attribute as HttpApiKey).httpApi;
}
}
}
}
本文来自博客园,作者:萧然CS,转载请注明原文链接:https://www.cnblogs.com/z-c-s/p/15112849.html