gpt4 book ai didi

c# - 如何编写与基类一起使用的扩展方法

转载 作者:行者123 更新时间:2023-11-30 13:36:22 26 4
gpt4 key购买 nike

想法是使用扩展方法来扩展我的功能。

所以不要有这样的东西:

 return Add(Add(storage.GetFirst(), 3), 7);

我想要这样的东西:

return storage.GetFirst().Add(3).Add(7);

扩展方法的问题在于它们在静态类中必须是静态的。这是我想要做的简化示例。

 public class Storage
{
public int GetFirst()
{
return 100;
}
public int GetAll(int x, int y)
{

// ...
return x + y;
}
}
public abstract class MyBase
{
protected Storage storage;
protected MyBase()
{
storage = new Storage();
}

public int Add(int what, int howMuch)
{
return storage.GetAll(what, howMuch);
}

}

public class MyClass : MyBase
{
public int method1()
{
return Add(Add(storage.GetFirst(), 3), 7);

//I want have something like this:
// return storage.GetFirst().Add(3).Add(7);
}
}

类(class)之外的类 Storage、MyBase 和 MyClass 不能是静态的。逻辑被简化为具有干净简单的示例,因此类之间的关系必须保持不变。我想要做的是让 Add 方法成为扩展方法,但让其他一切都“更不一样”。

这可能吗?如何做?

最佳答案

另一种解决方案是让您的 Storage 类实际存储一些东西:

public class Storage
{
private int currentValue;

public Storage GetFirst()
{
this.currentValue = 100;
return this;
}

public Storage Add(int toAdd)
{
this.currentValue += toAdd;
return this;
}

public int GetResult()
{
return this.currentValue;
}
}

这样你的调用将是:

int result = new Storage().GetFirst().Add(3).Add(5).GetResult();

关于c# - 如何编写与基类一起使用的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34525879/

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