我們有以下代碼,除非我們強制惰性加載器停止惰性,否則它會拋出一個
System.MissingMemberException:“延遲初始化的型別沒有公共的、無引數的建構式。”
例外。至少,對于我們已經擁有值并且我們只是讓惰性加載器反芻它的情況。
我的問題是——為什么?為什么會發生這種情況,我該怎么做才能使我們不需要包括在內var _ = _lazyChild.Value;?
public class MyContainedClass
{
private readonly int _id;
public MyContainedClass(int id) => _id = id;
}
public class MyContainer
{
private readonly Lazy<MyContainedClass> _lazyChild;
public MyContainer(MyRepository repo, int? childId, MyContainedClass child = null)
{
ChildId = childId;
if (childId != null)
{
_lazyChild = new Lazy<MyContainedClass>(() => child);
//Without the below line, later accessing _lazyAnswerGroup will throw:
//System.MissingMemberException: 'The lazily-initialized type does not have a public, parameterless constructor.'
var _ = _lazyChild.Value;
}
else
{
_lazyChild = new Lazy<MyContainedClass>(() => ChildId.HasValue ? repo.Get(ChildId.Value) : null);
};
}
public int? ChildId { get; set; }
public MyContainedClass Child => _lazyChild.Value;
}
旁注 - 是的,我知道有一個錯誤,您傳入一個子元素,然后再更改 ChildId。我假設這無關緊要。
uj5u.com熱心網友回復:
我想我已經想通了。我們還呼叫了一種方法,該方法使用反射在記憶體中制作物件的深拷貝。顯然,這不會呼叫非無引數建構式,因此Lazy<>s 沒有被正確初始化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458722.html
