[英]Non-null class default in C#
If I default(RefType)
I get null
. 如果我
default(RefType)
我得到null
。 If I default(ValType)
I get a ValType
with default
-ed properties. 如果我的
default(ValType)
我得到一个带有default
-ed属性的ValType
。 That's fine. 没关系。
But I want a ref-type with val-type default
semantics; 但是我想要一个具有val-type
default
语义的ref-type; particularly for subtypes. 特别是对于亚型。 Is this possible?
这可能吗?
Say, I expose an interface, IExtension
. 说,我公开了一个接口
IExtension
。 Someone implements it as a class as FooExtension
How can I most easily get " default
" instances of FooExtension
as an "empty" class (and, equally importantly, types derived of FooExtension
) without having to change the implementation? 有人将其作为
FooExtension
类FooExtension
如何最轻松地将FooExtension
“ default
”实例FooExtension
为“空”类(以及同样重要的是FooExtension
派生的FooExtension
),而不必更改实现?
This is important to me; 这对我很重要; I need to create non-
null
, "empty" instances of the derived types, so that they can be populated by a dynamic UI. 我需要创建派生类型的非
null
“空”实例,以便可以由动态UI填充它们。
I'm guessing the answer will be something to the effect of iterating properties via reflection, but perhaps there's a better (read: cleaner) way. 我猜测答案将是通过反射迭代属性的效果,但是也许有更好的方法(阅读:更简洁)。
I would just use structs, but the non-inheritable constraint, paired with the semantics of the types I'm describing being wrong, makes me wary (read: nope) 我只使用结构,但不可继承的约束与我描述的错误类型的语义配对,使我警惕(阅读:nope)
tl;dr: how do I get default classes like default structs, with inheritance supported implicitly. tl; dr:如何获取默认类(如默认结构),并隐式支持继承。
One option is FormatterServices.GetUninitializedObject
which allocates an instance without calling any constructors. 一个选项是
FormatterServices.GetUninitializedObject
,它分配实例而不调用任何构造函数。 Generally, that is deeply confusing unless you eventually call one of the types constructors or initialize the object fully. 通常,除非最终调用类型构造函数之一或完全初始化对象,否则这将造成极大的混乱。 As the name suggests, it is intended for creation of objects from serialized data but which might not have 0-arity constructors.
顾名思义,它旨在从序列化数据创建对象,但可能没有0 arity构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.