gpt4 book ai didi

c# - 关于C#中流畅接口(interface)的问题

转载 作者:太空狗 更新时间:2023-10-29 22:35:19 25 4
gpt4 key购买 nike

我有以下类(class):

public class Fluently
{
public Fluently Is(string lhs)
{
return this;
}
public Fluently Does(string lhs)
{
return this;
}
public Fluently EqualTo(string rhs)
{
return this;
}
public Fluently LessThan(string rhs)
{
return this;
}
public Fluently GreaterThan(string rhs)
{
return this;
}
}

在英语语法中,你不能有“is something equal to something”或“do something greater than something”,所以我不希望 Is.EqualTo 和 Does.GreaterThan 成为可能。有什么办法可以限制吗?

var f = new Fluently();
f.Is("a").GreaterThan("b");
f.Is("a").EqualTo("b"); //grammatically incorrect in English
f.Does("a").GreaterThan("b");
f.Does("a").EqualTo("b"); //grammatically incorrect in English

谢谢!

最佳答案

要强制执行这种类型的事情,您需要多种类型(以限制从哪个上下文中可用的内容)——或者至少需要几个接口(interface):

public class Fluently : IFluentlyDoes, IFluentlyIs
{
public IFluentlyIs Is(string lhs)
{
return this;
}
public IFluentlyDoes Does(string lhs)
{
return this;
}
Fluently IFluentlyDoes.EqualTo(string rhs)
{
return this;
}
Fluently IFluentlyIs.LessThan(string rhs)
{
return this;
}
Fluently IFluentlyIs.GreaterThan(string rhs)
{
return this;
}
}
public interface IFluentlyIs
{
Fluently LessThan(string rhs);
Fluently GreaterThan(string rhs);
}
public interface IFluentlyDoes
{ // grammar not included - this is just for illustration!
Fluently EqualTo(string rhs);
}

关于c# - 关于C#中流畅接口(interface)的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1304510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com