如何将运算符函数添加到原始数据类型 C#
How to add an operator function to a primative data type c#
所以我想做的是向原始数据类型添加一个运算符,其工作方式如下。
int m_number = 10;
m_number.CheckCondition (1,10);
CheckCondition 函数像这样工作
public bool CheckCondition (<The m_number variable>,int t_lower,int t_upper);
现在我可能弄错了,但我想我记得看到过这样做的方法,但再也找不到它的参数:(m_number 变量)类似于
this <Word I Forgot> m_number
作为第一个参数。
有谁知道这是否可行,如果可行,我必须做什么。
提前致谢。
您正在寻找 extensions。你可以这样创建它
public static class MyExtensions
{
public static bool IsBetween(this int i, int lower, int upper)
{
return lower < i && upper > i;
}
}
然后在任何 int
:
上使用它
bool check = 1.IsBetween(0, 10);
请注意,由于 int
是 value 类型,因此您无法更改它(就像在 i.ChangeSign()
中更改 [=15= 的实际值一样) ]).如果需要,您只能 return 更改值。
所以我想做的是向原始数据类型添加一个运算符,其工作方式如下。
int m_number = 10;
m_number.CheckCondition (1,10);
CheckCondition 函数像这样工作
public bool CheckCondition (<The m_number variable>,int t_lower,int t_upper);
现在我可能弄错了,但我想我记得看到过这样做的方法,但再也找不到它的参数:(m_number 变量)类似于
this <Word I Forgot> m_number
作为第一个参数。
有谁知道这是否可行,如果可行,我必须做什么。
提前致谢。
您正在寻找 extensions。你可以这样创建它
public static class MyExtensions
{
public static bool IsBetween(this int i, int lower, int upper)
{
return lower < i && upper > i;
}
}
然后在任何 int
:
bool check = 1.IsBetween(0, 10);
请注意,由于 int
是 value 类型,因此您无法更改它(就像在 i.ChangeSign()
中更改 [=15= 的实际值一样) ]).如果需要,您只能 return 更改值。