【问题标题】:c# implicit operator a matrix with parameters时间:2019-05-10 标签:c#implicit operator a matrix with parameters
【发布时间】:2013-05-31 14:02:21
【问题描述】:

我有这门课:

public class SmartTable : DataTable
{
    public string this[int Row, int Column]  { ... }
    public string this[int Row, string Column]  { ... }
}

我想在 THIS[,] 上添加一个隐式运算符

那么我可以使用:

string s = smartT[a,b];

int i = smartT[a,b];

我用谷歌搜索了这个,但我什至不知道如何搜索它。

我尝试过(基于 IntelliSense)声明如下内容:

public static implicit operator int[int r, int c](...) {...}

public static implicit operator int (SmartTable sm, int a, int b)

并且不工作。

谢谢

=== 编辑 ===

这是一个DataTable,一个表有字符串,整数,...

我想避免每次使用此表时都放入 Convert.To--(...)...

如果我尝试将字段放在 int 上,是因为它是一个整数字段... 我正在使用的解决方案是 create iGet(int C, int R), sGet(...), dGet(...)

【问题讨论】:

  • 问题是您似乎想要从 stringint 的隐式转换,但这是不可能的:语言不提供它,并且您无法在以下情况下创建用户定义的转换两种类型都是内置的。
  • @dlev 我不明白你的评论,或者我无法解释我想要什么...内部隐式代码将是 Convert.toInt() 或 .ToString()...
  • 如果您的smartT[a,b] 为两个重载都返回string,您希望如何将其转换为int?它只是对字符串值执行Int32.Parse 吗?您是否曾经返回无法转换为整数的字符串(例如“Hello World!”)?
  • @Rafael 你可以这样做,当然,但我的意思是它不能隐式:你需要明确地这样做(可能使用一个名为@的方法987654332@,可能带有实际返回int 的索引器。)

标签: c# matrix operator-keyword implicit


【解决方案1】:

如果您可以更改SmartTable 设计以返回或使用自定义类而不是原始string 类型,那么您可以将自己的隐式转换添加到intstring

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!”),它将抛出一个通常与best practices 相悖的异常,并且对于利用您的API 的开发人员来说是意料之外的。

【讨论】:

  • 谢谢,关于“最佳实践”,它是一个 DataTable,如果有人试图将产品描述放入 int 变量中,它应该会抛出错误...
猜你喜欢
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-21
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多