How do I get the custom attribute value of a field? [duplicate]
以取得字串最大長度為例子,取得成員的StringLength屬性
程式碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace RetriveClassAttribute
{
class Program
{
static void Main(string[] args)
{
foreach (var prop in typeof(RetriveClassAttribute).GetProperties())
{
var attrs = (StringLengthAttribute[])prop.GetCustomAttributes
(typeof(StringLengthAttribute), false);
foreach (var attr in attrs)
{
Console.WriteLine("{0}: {1}", prop.Name, attr.MaximumLength);
}
}
Console.ReadLine();
}
}
class RetriveClassAttribute
{
[StringLength(30)]
public string FirstMember { get; set; }
}
}