在C#中,是否有一种方法可以强制在对象初始化器中初始化某些属性
本文关键字:初始化 对象 属性 一种 是否 方法 | 更新日期: 2023-09-27 18:21:36
考虑以下代码:
public class ClassA
{
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
// Somewhere else
var obj = new ClassA
{
PropertyA = 1,
// Question:
// How do we force PropertyB to be set here without making it a parameter in the constructor?
// Ideally in compile time so that the code here would cause a compile error.
};
动机:当我试图通过属性而不是构造函数来注入依赖关系时,我想到了这个问题。
也许您没有意识到这一点,但您可以将对象初始化器与构造函数结合起来。
因此,您可以在构造函数中强制初始化,并且仍然允许像这样的对象初始化程序:
public class ClassA
{
public ClassA(int propertyB)
{
PropertyB = propertyB;
}
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
因此:
var obj = new ClassA(2 /*Property B*/)
{
PropertyA = 1
};
然而,在回答您的问题时:不,您不能强制在对象初始化程序中初始化属性。