Properties 设置只读;“家长”;来自父对象的子对象中的属性
我试图重现某些WinForms控件(如Properties 设置只读;“家长”;来自父对象的子对象中的属性,properties,parent-child,getter-setter,Properties,Parent Child,Getter Setter,我试图重现某些WinForms控件(如DataGridView和DataGridViewColumn)中的行为,其中子对象具有指向父对象的属性。此属性通常是只读的,但在调用父级的Add()方法后,它会以某种方式发生更改 在我的代码中,我有两个类,DataGroup和DataEntry,后者是子对象 如果我简单地实现了如下内容: public class DataEntry { public DataGroup Parent { get; set; } } public class Da
DataGridView
和DataGridViewColumn
)中的行为,其中子对象具有指向父对象的属性。此属性通常是只读的,但在调用父级的Add()
方法后,它会以某种方式发生更改
在我的代码中,我有两个类,DataGroup
和DataEntry
,后者是子对象
如果我简单地实现了如下内容:
public class DataEntry
{
public DataGroup Parent { get; set; }
}
public class DataGroup
{
public List<DataEntry> DataEntries { get; set; }
public DataGroup()
{
DataEntries = new List<DataEntry>();
}
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
DataEntries.Add(de);
de.Parent = this;
}
}
如果我想通过设置其父属性来添加子对象,但如果调用DataGroup.add()
正如我已经说过的,WinForms控件不能直接在子控件中更改父属性是很正常的,但是在从父控件调用Add方法之后,该属性就会更改。
我无法找到链接,这是父对象修改子对象中属性的一种方式,除非该属性是公共的或通过方法公开的,这两种方式都有可能绕过我的检查并最终产生错误。如果您只想对外部方隐藏该方法,可以将该方法声明为内部方法
internal void SetParent(DataGroup dg)
{
//code to set parent
}
我从未尝试过这个,但它也可能有效。我一直都是私下做的
public DataGroup Parent { get; internal set; }
另一个对自己隐藏多一点的方法是使用显式接口实现。甚至把它和内部结合起来,从外部隐藏起来。当显式实现接口时,调用该方法的唯一方法是首先将对象强制转换到接口。我想这样的办法行得通
internal interface ISetParent
{
void SetParent(DataGroup dg);
}
public class DataEntry : ISetParent
{
void ISetParent.SetParent(DataGroup dg)
{
Parent = dg;
}
public DataGroup Parent { get; private set;}
}
public class DataGroup
{
public List<DataEntry> DataEntries { get; set; }
public DataGroup()
{
DataEntries = new List<DataEntry>();
}
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
DataEntries.Add(de);
((ISetParent)de).SetParent(this);
}
}
内部接口ISetParent
{
void SetParent(数据组dg);
}
公共类数据项:ISetParent
{
void ISetParent.SetParent(数据组dg)
{
父代=dg;
}
公共数据组父级{get;private set;}
}
公共类数据组
{
公共列表数据项{get;set;}
公共数据组()
{
DataEntries=新列表();
}
公共无效添加(数据输入de)
{
//检查这里的东西
// ...
//
DataEntries.Add(de);
((ISetParent)de).SetParent(this);
}
}
实际上,我想对代码的其他部分隐藏它,以避免出错。如果我将它声明为内部,我仍然可以在我的程序集中访问它…您可以通过实现显式接口实现来隐藏它。这样,只有先将对象强制转换到其接口,才能访问该方法。也许把它和内部的结合起来。
internal interface ISetParent
{
void SetParent(DataGroup dg);
}
public class DataEntry : ISetParent
{
void ISetParent.SetParent(DataGroup dg)
{
Parent = dg;
}
public DataGroup Parent { get; private set;}
}
public class DataGroup
{
public List<DataEntry> DataEntries { get; set; }
public DataGroup()
{
DataEntries = new List<DataEntry>();
}
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
DataEntries.Add(de);
((ISetParent)de).SetParent(this);
}
}