簡體   English   中英

在父方法中返回子類型的通用方法

[英]Generic method to return a child type in a parent method

我已經在C#中嘗試了擴展方法幾周,並且遇到了一些有趣的事情。 我已經嘗試過為DTO構建泛型,如下所示:

public class ParentDto{
    public string attrStr{get;set;}
}

public static class ParentDtoExtensions{
    public static T AttrStr<T>(this T parentDto, string attrStr)
    where T:ParentDto{
        parentDto.attrStr = attrStr;
        return parentDto;
    }
}

然后在子類中:

public class ChildDto:ParentDto{
    public string childAttrStr{get;set;}
}

public static class ChildDtoExtensions{
    public static T ChildAttrStr<T>(this T childDto, string childAttrStr)
    where T:ChildDto{
        childDto.childAttrStr = childAttrStr;
        return childDto;
    }
} 

然后讓我像這樣鏈接我的方法:

return ((new ChildDto()).AttrStr("someString").ChildAttrStr("someOtherString"));

這真的吸引了我。 能夠使用monad-ish setter以及其他方法返回調用類型對於鏈接代碼塊非常方便。

但是,我希望能夠將setter方法集成到我認為它們真正所屬的父類中,同時保持上面顯示的現有代碼流,但是我不知道實現返回孩子的方法的方法。實現類的類。 就像是:

public class ParentDto{
    public string attrStr{get;set;}

    public T AttrStr<T>(string attrStr)
    where T:ParentDto{
        parentDto.attrStr = attrStr;
        return parentDto;
    }
}

但這對編譯器(?)不起作用,因為它不知道調用類型。 有誰知道如何做到這一點?

請記住,我不是在尋求有關現有實現的代碼味道的建議,因為我敢肯定有更多的C#方式可以實現此目的。

您可以執行以下操作,但是IMO的擴展方法要好得多:

public class ParentDto<T> where T : ParentDto<T> {
    public string attrStr{get;set;}

    public T AttrStr(string attrStr) {
        this.attrStr = attrStr;
        return (T)this;
    }
}
public sealed class ChildDto : ParentDto<ChildDto> {
    public string childAttrStr{get;set;}
    public ChildDto ChildAttrStr(string childAttrStr) {
        this.childAttrStr = childAttrStr;
        return this;
    }
}

有關此模式的更多信息以及為什么應盡可能避免使用它,請參閱Eric Lippert的博客文章Curiouser and curiouser

就是說,我同意這是一種代碼味道。 您應該只使用屬性設置器,而不要使用流利的語法。 但是,由於您不在那里尋求建議,因此我將保留它。

如果您要做的只是在新對象上設置屬性,則可以使用對象初始化程序來代替:

return new ChildDto()
    {
        attrStr = "someString",
        childAttrString = "someOtherString"
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM