【问题标题】:How to copy a record to another record using the with keyword in C# net5.0如何在 C# net5.0 中使用 with 关键字将一条记录复制到另一条记录
【发布时间】:2021-09-18 19:03:42
【问题描述】:

我正在学习 C# 并尝试使用记录编写代码,同时还实现了依赖倒置。

我有一个工厂类,我用它来创建我的记录实例,称为人类。

我还使用了一个人类接口,我认为这会使我的代码更松散耦合,从而实现依赖倒置(我希望如此)。

我创建了一个名为 Paul 的人类实例。当我尝试使用

关键字,以便我可以将记录名称更改为 James,但出现错误。

paul 在这里不为空。接收者类型“IHuman”不是有效的记录类型。

我做错了什么?这是我的代码..

程序.cs

class Program
{
    static void Main(string[] args)
    {
        IHuman paul = Factory.CreateHuman(37, "Male", 5.11, "paul lag");
        IHuman james = paul with { Name="james bond"};
        Console.WriteLine(paul);
        Console.WriteLine(james);
        paul.Living();
        Console.ReadLine();
    }
}

人类.cs

 public record Human(int Age, string Sex, double Height, String Name) : IHuman
{
    public void Living()
    {
        Console.WriteLine("This Human is Living");
    }
}

Factory.cs

 public static class Factory
{
    public static IHuman CreateHuman(int age,string sex, double height,string name)
    {
        return new Human(age,sex,height,name);
    }
}

IHuman.cs

public interface IHuman
{
    int Age { get; init; }
    double Height { get; init; }
    string Name { get; init; }
    string Sex { get; init; }

    void Deconstruct(out int Age, out string Sex, out double Height, out string Name);
    bool Equals(Human? other);
    bool Equals(object? obj);
    int GetHashCode();
    void Living();
    string ToString();
}

【问题讨论】:

  • 问题在于IHuman 是一个接口,因此编译器无法确定它是否会成为记录。您可以使用(Human)paul with { Name = "james bond" }Human paul = Factory.CreateHuman(37, "Male", 5.11, "paul lag") as Human;,但这是代码异味。
  • @Cid,实际上,我删除了我的离题评论。

标签: c# .net oop


【解决方案1】:

问题在于IHuman 是一个接口,因此编译器无法确定它是否会成为记录。考虑另一个实现相同接口的class 的情况,如果您尝试使用with,则会引发异常。

您可以在执行with 时转换为Human

IHuman james = (Human)paul with { Name = "james bond" } 

或者当你首先得到对象时:

Human paul = Factory.CreateHuman(37, "Male", 5.11, "paul lag") as Human; 

但它们都是代码味道。不过,我真的不认为首先需要这个界面。您基本上复制了record 中的所有方法。所以我的建议是摆脱它并直接使用Human 对象。

【讨论】:

  • 感谢您的回复。但是由于我的应用程序现在依赖于完整的实现而不是接口IHuman提供的抽象实现,所以在main方法中直接使用Human会不会违背依赖倒置?
  • DI 对有逻辑的东西很有用,对于只包含数据的对象几乎没用。
猜你喜欢
  • 1970-01-01
  • 2017-04-19
  • 1970-01-01
  • 2019-09-30
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多