C# 特性參數(注解屬性加在參數前面)


特性參數

webapi 框架里有很多特性參數,為了解除一些新人的疑惑,寫個小例子分享下。


  class Program
{
    static void Main(string[] args)
    {
        var message = new MessageData {

            Header="header...",
            Body="body....",
            Footer="footer...",
        };

        Type objT = typeof(Program);
        Type fromBodyT = typeof(FromBodyAttribute);
        MethodInfo method = objT.GetMethod("Test");

        ParameterInfo[] paramsInfo = method.GetParameters();
        var parameters= new List<object>(paramsInfo.Length);
        foreach (ParameterInfo parameterInfo in paramsInfo)
        {
            var parameter = new object();
            if (parameterInfo.CustomAttributes.Any(i => i.AttributeType == fromBodyT))
                parameter = message.Body;
            parameters.Add(parameter);
        }


        object result = method.Invoke(null, parameters.ToArray());
        Console.WriteLine(result);


    }
    public class FromBodyAttribute : Attribute
    {
    }
    public static string Test([FromBody] string body)
    {
        return body;
    }
    class MessageData
    {

        public string Body { get; set; }
        public string Header { get; set; }
        public string Footer { get; set; }

    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM