【发布时间】: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,实际上,我删除了我的离题评论。