[英]How to tell if you are in your own constructor, or your base class's constructor in c#
如果一个Sub类调用它的基类Super的构造函数,有没有办法告诉它不仅仅是对Super的构造函数的调用呢?
我正在将数据从磁盘加载到对象中,我想验证使用反射所有字段都不为空。 但是,如果我调用我的基本构造函数,那么在所有构造函数完成之前检查它是不合适的。 例:
class Super
{
string s;
float? f;
public Super(List<string> lines)
{
//initialize s and f based on lines
if (notFromSubclassConstructor))
{
AssertInitialized(this);
}
}
public static void AssertInitialized(Super super)
{
// Iterate through every field and make sure it isnt null
// I already know how to do this part. If we find a null
// field we throw an exception.
}
}
class Sub : Super
{
string something;
int? somethingElse;
public Sub(List<string> lines)
: base(lines) //we dont want to AssertInitialized inside here, we arent done yet!
{
//initialize blah blah
if (notFromSubclassConstructor))
{
AssertInitialized(this);
}
}
}
我想避免传递某种布尔值,表明我来自哪里,因为那是丑陋的。 我可以用反射或其他方式以某种方式做到这一点吗? 随意建议替代范例。
那么你可以使用:
if (GetType() == typeof(Super))
这将决定对象的实际类型。
但无论如何,我真的不确定这个模式。 为什么不使Super.AssertInitialized
只检查Super
的字段, Sub.AssertInitialized
检查Sub
的字段? 使它们成为私有方法,并从两个构造函数中调用它们。
编辑:为了清楚,我会明确使用相关字段进行检查 - 不要在这里使用反射迭代 - 你知道所有字段是什么,所以为什么不使用它们?
只需让层次结构中的每个类检查自己的字段。 如果在基类构造函数中抛出异常,派生类构造函数将永远不会运行,因为异常将直接传播给调用者。
这允许每个类对自己的数据负责,这些数据随着时间的推移应该更易于维护。 (它还允许您直接检查初始化,而不是尝试依赖反射,这不仅更快,而且更易于使用和写入。)
好吧,或者在层次结构中最顶级的类中添加数据一致性控件,或者添加构造对象的Factory
,并检查其数据。 恕我直言是最“明确”的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.