c#反射及继承

**

c#反射及继承

详解反射请点击:http://www.cnblogs.com/landeanfen/p/4642814.html
**
SonClass1.cs和BaseClass.cs是放在一个文件夹里面CodeLib

在文件夹里定义的一个类
BaseClass.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Demo2.CodeLib
{
    /// 
    /// 基类
    /// 
    public class BaseClass
    {
        /// 
        /// 虚方法
        /// 
        public virtual void Operater()
        {

        }
        /// 
        /// string类型的方法
        /// 
        /// 
        public string GetResult()
        {
            Operater();
            return outStr;
        }

        protected string Method = "";
        public string _Method
        {
            set { Method = value; }
        }

        protected string outStr = "";
    }
}

在文件夹里定义的另一个类
SonClass1.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Demo2.CodeLib
{
    //子类继承父类
    public class SonClass1 : BaseClass
    {
        //重写虚方法
        public override void Operater()
        {
            //Method私有字段
            switch (Method)
            {
                case "Say":
                    Say();
                    break;
                default:
                    break;
            }
        }

        private void Say()
        {
            outStr = "SonClass1.Say";
        }
    }
}

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Demo2.CodeLib;
using System.Reflection;

namespace Demo2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //初始赋值
            string OperateStr = "SonClass1,Say";
            //请求ExecuteStr方法输出参数的值
            Response.Write(ExecuteStr(OperateStr));
        }

        private string ExecuteStr(string Str)
        {
            //以逗号为分隔符取第一个数据
            string strClassName = Str.Split(',')[0];
            //以逗号为分隔符取第二个数据
            string method = Str.Split(',')[1];
            //反射创建类别
            BaseClass bc = (BaseClass)Assembly.Load("Demo2").CreateInstance("Demo2.CodeLib." + strClassName, true);
            bc._Method = method;//传入方法
            return bc.GetResult();//获取最终数据
        }
    }
}

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo2._Default" %>





    无标题页


    

你可能感兴趣的:(C#基础)