C# 泛型

学习中

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

namespace ConsoleApp1
{
    class UserDefineType1
    {
        public int IntInstance1 {  get; set; }
        public int IntInstance2 {  get; set; }
    }
    class UserDefineType2
    {
        public string StringInstance1 { get; set; }
        public string StringInstance2 { get; set; }
    }

    class GenericBaseClass where T : class
    {
        private T value;
        public int IntProperty { get; set; }
        public string StringProperty { get; set; }

        public GenericBaseClass(int inyParameter,string stringParameter)
        {
            IntProperty = inyParameter;
            StringProperty = stringParameter;
        }   

        public void GetValueFunction()
        {
            PropertyInfo[] objects = value.GetType().GetProperties();//通过反射获取所有属性
            foreach (PropertyInfo obj in objects)
            {
                Console.WriteLine(obj.GetValue(value));//通过反射获取所有属性的值
            }
        }

        public void SetValueFunction(T value)
        {
            this.value = value;
        }
    }

    class GenericClass1 : GenericBaseClass where UserDefineType1 : class
    {
        public GenericClass1(int intParameter,string stringParameter):base(intParameter, stringParameter)
        {

        }
    }

    class GenericClass2 : GenericBaseClass where UserDefineType2 : class
    {
        public GenericClass2(int intParameter, string stringParameter) : base(intParameter, stringParameter)
        {

        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            GenericClass1 genericClass1Instance=new GenericClass1(0,"Hello0");
            GenericClass2 genericClass2Instance=new GenericClass2(1,"Hello1");

            UserDefineType1 userDefineType1 = new UserDefineType1();
            UserDefineType2 userDefineType2 = new UserDefineType2();

            userDefineType1.IntInstance1 = 0;
            userDefineType1.IntInstance2 = 1;

            userDefineType2.StringInstance1 = "Hello0";
            userDefineType2.StringInstance2 = "Hello1";

            genericClass1Instance.SetValueFunction(userDefineType1);
            genericClass2Instance.SetValueFunction(userDefineType2);

            genericClass1Instance.GetValueFunction();
            genericClass2Instance.GetValueFunction();

            Console.WriteLine($"{genericClass1Instance.IntProperty},{genericClass1Instance.StringProperty}");
            Console.WriteLine($"{genericClass2Instance.IntProperty},{genericClass2Instance.StringProperty}");




            Console.ReadKey();


        }
    }
}

你可能感兴趣的:(c#,开发语言)