gpt4 book ai didi

c# - 覆盖对象返回值

转载 作者:IT王子 更新时间:2023-10-29 04:23:03 25 4
gpt4 key购买 nike

我正在尝试将对象与 int 值进行比较,例如

if (myObject - 5 == 0)
doSomething();

我的类可能看起来像这样:(删除了大多数 setter/getter,所以不要介意所有变量都是私有(private)的)

public class SomeClass
{
public string name;
private int minValue;
private int maxValue;
private int currValue;

public int getCurrentValue()
{
return currValue;
}
}

我想要实现的是这样的:

someClassInstance - 5;

等于

someClassInstance.getCurrentValue() - 5;

我可以重写对象作为一个 int(它自己的变量)而不只是一个对象吗?

最佳答案

可能operator是这样的?

public class SomeClass {
...

public static int operator -(SomeClass left, int right) {
if (Object.ReferenceEquals(null, left))
throw new ArgumentNullException("left");

return left.getCurrentValue() - right;
}
}

...

SomeClass someClassInstance = new SomeClass(...);

int result = someClassInstance - 5;

另一种可能性(基于隐式运算符)是在需要时 SomeClass 隐式转换为int:

public class SomeClass {
...

// Whenever int is requiered, but SomeClass exists make a conversion
public static implicit operator int(SomeClass value) {
if (Object.ReferenceEquals(null, value))
throw new ArgumentNullException("value");

return value.getCurrentValue();
}
}

...

SomeClass someClassInstance = new SomeClass(...);

int result = someClassInstance - 5;

关于c# - 覆盖对象返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21425969/

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