C# 无法将“数据”类型的对象转换为“System.IConvertible”类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12792985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:29:14  来源:igfitidea点击:

Unable to cast object of type 'Data' to type 'System.IConvertible'

c#asp.net

提问by user1375481

Im getting this error "Unable to cast object of type 'Data' to type 'System.IConvertible'." in my code

我收到此错误“无法将 'Data' 类型的对象转换为 'System.IConvertible' 类型。” 在我的代码中

foreach (Data p in clusters[i])
 {
   for(int z=0; z<53;z++)
    {
      if (values[z] = Convert.ToInt32(p))
      {
         lray[z].BackColor = colorSet[i];
      }
    }
  }

"values" is an integer array and p is from Data class

"values" 是一个整数数组,p 来自 Data 类

class Data
    {

        public int X, ClusterId;
        public Data(int x)
        {
            this.X = x;
        }
        public override string ToString()
        {
            return String.Format("({0})", X);
        }
        public static int DistanceSquared(Data p1, Data p2)
        {
            int diffX = p2.X - p1.X;
            return diffX * diffX;
        }
    }

采纳答案by nunespascal

Your intent is not clear from your code.

您的代码并不清楚您的意图。

pin an object of Data. Seems you want to access the data you have saved in the member X of p

p在 的对象中Data。好像要访问p的成员X中保存的数据

But you could do it like this

但你可以这样做

foreach (Data p in clusters[i])
 {
   for(int z=0; z<53;z++)
    {
      if (values[z] == p.X)
      {
         lray[z].BackColor = colorSet[i];
      }
    }
  }

回答by Aamir

Simply what the error says. You have to implement IConvertible in your Data class for this to be used like this.

只是错误所说的内容。您必须在 Data 类中实现 IConvertible 才能像这样使用它。

IConvertible Interface

可转换接口

回答by Alexei Levenkov

Youe Dataclass clearly does not implement System.IConvertible. So you can either do so or perform some other check in your if.

YoueData类显然没有实现System.IConvertible。因此,您可以这样做,也可以在 if 中执行一些其他检查。

class Data : System.IConvertible
{// implement necessary methods of System.IConvertible here 
}

Side note: =is assignment, you likely meant if (values[z] == ...)

旁注:=是赋值,你可能的意思是if (values[z] == ...)