父类操作子类

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections.ObjectModel;
namespace 泛基
{
    class Program
    {
        static void Main(string[] args)
        {
            MyBase<MyClass> c = new MyClass();
            c.say();
            Console.ReadLine();
        }
    }

    //父类操作子类(因为父类不知道被谁继承)
    //父类的静态属性,可以在子类的Static构造函数中初始化为不同的值
 public abstract class MyBase<T> where T :MyBase <T> //被人肉编译器 @vczh 发现少写了<T>

{

    public static string DataForThisType {get;set;}
    public static T Instance{get;protected set;}
    //老赵说的邪恶的部分:让父类操作子类出现了
    public static readonly Dictionary<string, MemberInfo> Members
        =typeof(T)
            .GetMembers()
            .ToDictionary(x=>x.Name);

    public void say() {

        foreach (var kv in Members)
        {
            Console.WriteLine(kv.Key+"="+kv.Value);
        }
    }
    
         
}



public class MyClass:MyBase<MyClass>
{

    static MyClass() //第一次new的时候执行,并且只执行一次
    {
        Console.WriteLine("static MyClass()");
        DataForThisType =string.Format(
            "MyClass got {0} members",Members.Count);
        Instance = new MyClass();
    }

}

}

 

posted @ 2017-03-24 10:37  甜菜波波  阅读(257)  评论(0编辑  收藏  举报