ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# 特性实验

2022-01-15 15:31:38  阅读:105  来源: 互联网

标签:Console c# System 特性 class 实验 WriteLine type public


1.概要

1.1特性的价值,就是作为类的元数据使用,不是对象的元数据,因为只有类有特性。而对象没有。或者说对象没有特性的那个概念,因为一个类无论创建多少对象,他的特性是固定的。

1.2 元数据的价值,就是可以通过对这个特性数据的赋值,改变类的运行行为。

2.代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace csharp特性
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("csharp特性");
            Program program = new Program();
            program.main();
            Console.ReadKey();
        }
        private void main() {
            test1();
            test2();
            test3();
        }
        private void test1() {
            Console.WriteLine("最简单的实验");
            A a = new A();
            Type type = a.GetType();
            FieldInfo f = type.GetField("mA1");
            TestAtrribute testAtrribute = f.GetCustomAttribute<TestAtrribute>();
            Console.WriteLine(testAtrribute.str);
        }
        private void test2() {
            Console.WriteLine("构造函数实验");
            B b = new B();
            Type type = b.GetType();
            FieldInfo f = type.GetField("mA1");
            Test2 testAtrribute = f.GetCustomAttribute<Test2>();
            Console.WriteLine(testAtrribute.value);
        }
        private void test3()
        {
            Console.WriteLine("赋值实验");
            C c = new C();
            Type type =c.GetType();
            FieldInfo f = type.GetField("mA1");
            Test3 testAtrribute = f.GetCustomAttribute<Test3>();
            Console.WriteLine(testAtrribute.Value);
        }
    }
    /// <summary>
    /// 最简单的实验
    /// </summary>
    class A {
        [TestAtrribute]
        public int mA1 = 5;
    }
    public class TestAtrribute : System.Attribute {
        public string str = "my is TestAtrribute";
    }
    /// <summary>
    /// 构造函数实验
    /// </summary>
    class B {
        [Test2(1)]
        public int mA1 = 5;
    }
    public class Test2 : Attribute {
        public int value;
        public Test2(int a) {
            value = a;
        }
    }
    /// <summary>
    /// 赋值实验
    /// </summary>
    class C {
        [Test3(Value=9)]
        public int mA1 = 5;
    }
    public class Test3: Attribute
    {
        public int Value { set; get; }
    }
}

3.运行

标签:Console,c#,System,特性,class,实验,WriteLine,type,public
来源: https://blog.csdn.net/xie__jin__cheng/article/details/122510722

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有