c#隐式运算符一个带参数的矩阵
本文关键字:一个 参数 运算符 | 更新日期: 2023-09-27 18:16:20
我有这样一个类:
public class SmartTable : DataTable
{
public string this[int Row, int Column] { ... }
public string this[int Row, string Column] { ... }
}
和i想在THIS[,]
上添加一个隐式操作符那么我可以使用:
string s = smartT[a,b];
或
int i = smartT[a,b];
我用谷歌搜索了一下,但我也不知道怎么搜索。
我尝试(基于智能感知)声明如下:
public static implicit operator int[int r, int c](...) {...}
或
public static implicit operator int (SmartTable sm, int a, int b)
和不工作
感谢===编辑===
这是一个数据表,一个表有字符串,整数,…
我想避免在每次使用这个表时使用put Convert.To——(…)
如果我试图把一个字段放在一个int,是因为它是一个整数字段…我使用的解决方案是创建iGet(int C, int R), sGet(…),dGet(…)
如果您可以更改SmartTable
设计以返回或使用自定义类而不是原始string
类型,那么您可以添加自己的隐式转换到int
或string
。
public class SmartTable : DataTable
{
//dummy/hard-coded values here for demonstration purposes
public DataValue this[int Row, int Column] { get { return new DataValue() {Value="3"}; } set { } }
public DataValue this[int Row, string Column] { get { return new DataValue() {Value="3"}; } set { } }
}
public class DataValue
{
public string Value;
public static implicit operator int(DataValue datavalue)
{
return Int32.Parse(datavalue.Value);
}
public static implicit operator string(DataValue datavalue)
{
return datavalue.Value;
}
}
和一些用法:
string s = smartT[0, 0];
int i = smartT[0, 0];
Console.WriteLine(s);//"3"
Console.WriteLine(i);//3
注意,这有点违背了隐式操作符的使用。例如,如果您的DataValue.Value
不可转换为int
(例如,如果它是"Hello World!"),它将抛出一个异常,这通常是违反最佳实践的,并且对于利用您的API的开发人员来说是意想不到的。