相关疑难解决方法(0)

深度克隆对象

我想做的事情如下:

MyObject myObj = GetMyObj(); // Create and fill a new object
MyObject newObj = myObj.Clone();
Run Code Online (Sandbox Code Playgroud)

然后更改未在原始对象中反映的新对象.

我不经常需要这个功能,所以当有必要的时候,我已经使用了创建一个新对象然后单独复制每个属性,但它总是让我觉得有更好或更优雅的处理方式情况.

如何克隆或深度复制对象,以便可以修改克隆对象而不会在原始对象中反映任何更改?

.net c# clone

2135
推荐指数
34
解决办法
77万
查看次数

从基类方法返回派生类型

我有一个类似于这个的类层次结构:

public class Base
{
    private List<string> attributes = new List<string>();

    public T WithAttributes<T>(params string[] attributes)
        where T : Base
    {
        this.attributes.AddRange(attributes);
        return this as T;
    }
}

public class Derived : Base
{
}
Run Code Online (Sandbox Code Playgroud)

我想以Base.WithAttributesfluent-api样式语法从派生类调用,并返回派生实例,如下例所示.

void Main()
{
    Derived d = new Derived();

    // CS0411 The type arguments for method 'UserQuery.Base.WithAttributes<T>(params string[])' cannot be inferred from the usage.
    d.WithAttributes("one", "two"); 

    // Works, but type arguments must be explicity specified. 
    d.WithAttributes<Derived>("one", "two");

    // Works without explicitly specifying, but …
Run Code Online (Sandbox Code Playgroud)

c# generics

8
推荐指数
1
解决办法
2779
查看次数

标签 统计

c# ×2

.net ×1

clone ×1

generics ×1