日期:2014-05-18  浏览次数:20994 次

MethodInfo Invoke 未将对象引用设置到对象的实例??
C# code

    public abstract class AbstractService
    {
        public abstract void Load();
        public abstract Int32 Save();
        public abstract object DataSource{ get; }
    }
    /// 数据服务的抽象化(数据服务的基类)
    public abstract class AbstractServiceDS<TDataTable, TAdapter> : AbstractService 
        where TDataTable : DataTable, new()
        where TAdapter : class, new ()
    {
        private TDataTable _table = null;
        private TAdapter _adapter = null;

        private MethodInfo _adMethodFill = null;
        private MethodInfo _adMethodUpdate = null;

        //
        // 无参数构造函数
        // 
        public AbstractServiceDS()
        {
            this._table = new TDataTable();
            this._adapter = new TAdapter();
            //初始化反射方法
            this.InitReflectionMethods();
        }
        //
        // 外部数据集的构造函数
        // 
        public AbstractServiceDS(TDataTable table, TAdapter adapter)
        {
            this._table = table;
            this._adapter = adapter;
            //初始化反射方法
            this.InitReflectionMethods();
        }
        //初始化反射方法
        private void InitReflectionMethods()
        {
            try
            {
                Type typeAdapter = typeof(TAdapter);
                this._adMethodFill = typeAdapter.GetMethod("Fill");
                this._adMethodUpdate = typeAdapter.GetMethod("Update", new Type[]{ typeof(TDataTable) });
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);                
            }
        }

        public override void Load()
        {
            object[] args = new object[] { this._table };
            _adMethodFill.Invoke(this._adapter, args);
        }
         //重写保存的虚方法     
        public override int Save()
        {
            int nRows = 0;
            try
            {
                object[] args = new object[] { this._table };
                nRows = (int)_adMethodUpdate.Invoke(this._adapter, args);//在这就跑出“未将对象引用设置到对象的实例? ”
                this._table.AcceptChanges();
                
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            return nRows;

        }
        public override object DataSource
        {
            get { return this._table; }
        }
        public TAdapter Adapter
        {
            get { return this._adapter; }
            protected set { this._adapter = value; }
        }
    }
}



我刚刚学c# 请前辈赐教

------解决方案--------------------
自己 debug 一下吧。

this.InitReflectionMethods(); 里的

 this._adMethodUpdate = typeAdapter.GetMethod("Update", new Type[]{ typeof(TDataTable) });

估计没有取到 Update 方法啊。
------解决方案--------------------
加一下BidingFlags试下。