在继承的类的构造函数中设置私有属性值 [英] Setting private property value in constructor of inherited class

查看:111
本文介绍了在继承的类的构造函数中设置私有属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无法修改的外部库的基类-这是相关的内容:

I've got a base class from an outside library that I can't modify - here's the relevant piece:

public class BaseClass
{
     List<string> _values;
     public Values { get { return _values; } }
}

我正在继承BaseClass,并且想将_values设置为从构造函数中的List(T)继承的类:

I am inheriting the BaseClass, and I want to set _values to a class that inherits from List(T) in the constructor:

public InheritingClass : BaseClass
{
     public InheritingClass():base()
     {
          //set base._values = new InhertingList<string>(); ?
     }
}

在那里设置base._values的最佳方法是什么?有没有一种方法可以找到值"所获取的私有变量,并进行设置以防将来将来对私有变量进行重命名?

What's the best way to set base._values there? Is there a way to find what private variable is fetched by Values and set that in case the private variable is renamed in the future?

我还有其他方法可以完成我需要做的事情,但是,如果我可以做到以下几点,那将比不设置私有财产价值而实现我的目标的任何方法都快得多.

There are other ways I can accomplish what I need to do, but if I could do the following, it would be quicker by far than any ways of achieving my goal without setting the private property value.

推荐答案

将其定义为私有是为了防止这种情况发生.

Keeping it private, by definition, is meant to prevent this exact scenario.

最好的选择是实施受保护的二传手:

The best option would be to implement a protected setter:

public class BaseClass
{
     public Values { 
        get { return _values; }
        protected set { _values = value; }
     }
}

这样,您的InheritingClass可以访问setter,并且可以执行以下操作:

This way, your InheritingClass has access to the setter, and can do:

this.Values = new InhertingList<string>(); 

但是由于您不能更改基类,因此从技术上讲,可以通过反射(在完全信任的情况下)做到这一点.不过,我不推荐这种方法:

But since you can't change the base class, it is, technically, possible to do this via reflection (in a full trust scenario). I don't recommend this approach, though:

FieldInfo field = typeof(BaseClass).GetField("_value", BindingFlags.Instance | BindingFlags.NonPublic );
field.SetValue(this, this.Values = new InhertingList<string>() );

顺带一提,做您尝试做的事情的危险是,您将把BaseClass定义的实现更改为您提供的内容.引入细微的错误非常容易,因为您(有目的地)破坏"了基类中的实现细节.

The danger of doing what you are attempting, btw, is that you're going to change the implementation defined by the BaseClass to something that you're providing. It's very easy to introduce subtle bugs, since you're (purposefully) "breaking" the implementation details in the base class.

我会尝试重新考虑您的算法,看看是否有另一种方法可以解决此问题.

I'd try to rethink your algorithm, and see if there's another way around this issue.

这篇关于在继承的类的构造函数中设置私有属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆