Overriden Properties和TargetInvocationException

时间:2012-05-17 01:17:57

标签: c#

我正在尝试从基础构造函数调用overriden属性,但我收到一个System.Reflection.TargetInvovationException(“对象引用未设置为对象的实例。”)。为什么抛出这个错误,可以做些什么来避免它?

我原本期望构造函数刚刚调用了overriden属性。

这是一个精简的例子:

// Call that generates exception
var foo = new Foo();

public class Foo : Bah {

    public Foo() : base("Foo!") {}

    public override string Name {
        get { return _name + "123"; }
        set { _name = value; }
    }
}

public class Bah {

    protected string _name;

    public Bah(string name) {
        Name = name; // << -- Exception here
    }

    public virtual string Name {
        get { return _name; }
        set { _name = value; }
    }
}

1 个答案:

答案 0 :(得分:1)

你还有其他一些问题。键入的代码有效。尝试这个功能齐全的程序来查看,打印(如预期的那样)“Foo!123”:

using System;

namespace Test
{
    public class Program
    {
        private static void Main()
        {
            var foo = new Foo();
            Console.WriteLine(foo.Name);
            Console.ReadKey();
        }
    }

    public class Foo : Bah
    {
        public Foo() : base("Foo!") { }

        public override string Name
        {
            get { return _name + "123"; }
            set { _name = value; }
        }
    }

    public class Bah
    {
        protected string _name;

        public Bah(string name)
        {
            Name = name; // << -- No Exception here (or anywhere!)
        }

        public virtual string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }
}

话虽这么说,在构造函数中调用虚方法(包括Property访问器方法)是一个非常糟糕的主意。它可能导致非常奇怪的行为,这可能是您真实代码中的罪魁祸首。

相关问题