我能实现在C#中,从派生类拷贝“的拷贝构造函数”? [英] Can I achieve a 'copy constructor' in C# that copies from a derived class?
问题描述
这是应用具体的例子来说明我的眼前的问题:
An application specific example to illustrate my immediate problem:
我有一个元数据提供程序类具有以下(有删节)接口:
I have a metadata provider class with the following (abridged) interface:
public class CtsDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
return metadata;
}
}
现在我想延长 ModelMetadata code>具有附加属性,这些填充并返回和
ExtendedModelMetadata code>的实例。我怎样才能很好地传达我的延长例如通过
base.CreateMetadata code>分配给
元
实例属性?我想,但没有为;
Now I would like to extend ModelMetadata
with additional properties, populate these and return and instance of ExtendedModelMetadata
. How can I nicely convey properties assigned to the metadata
instance by base.CreateMetadata
in my extended instance? What I would like but don't have is;
var metadata = (ExtendedModelMetadata)base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
我可以创建一个构造 ExtendedModelMetadata code>,需要一个
ModelMetadata code>参数,并明确赋予它的所有属性的比如正在建设中,但我想这一个更通用和更少的硬件codeD的方法。我该怎么办?
I can create a constructor for ExtendedModelMetadata
that takes a ModelMetadata
parameter and explicitly assigns all of it's properties to the instance being constructed, but I would like a more generic and less hard-coded approach for this. What can I do?
推荐答案
您可以使用 AutoMapper 实现这一目标。
You can use AutoMapper to achieve this.
Mapper.CreateMap<ModelMetaData , ExtendedModelMetadata>();
.NET Framework不提供了深刻的复印功能。
.NET Framework does not provide a deep copy feature.
这篇关于我能实现在C#中,从派生类拷贝“的拷贝构造函数”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!