将数据类型作为参数发送

本文关键字:参数 数据类型 | 更新日期: 2023-09-27 17:49:50

我正在尝试编写一个使用以下两个参数的方法:

ColumnToSort
ColumnType

我希望能够做到这一点的原因是,将两个东西解释为字符串可以给出不同的结果,而不是将相同的两个东西作为数字进行比较。例如

String: "10" < "2"
Double: 10 > 2 

基本上,我希望能够发送double或string数据类型作为方法参数,但我不知道怎么做,但这在c#中应该是可能的。

附录:

我想让我的方法看起来像:

InsertRow(customDataObj data, int columnToSort, DataType dataType){
    foreach(var row in listView){
        var value1 = (dataType)listView.Items[i].SubItems[columnToSort];
        var value2 = (dataType)data.Something;
        //From here, it will find where the data object needs to be placed in the ListView and insert it
    }
}

如何命名:

I think the above provides enough of an explanation to understand how it will be called, if there are any specific questions, let me know. 

将数据类型作为参数发送

可以使用Type作为参数类型。这样的

void foo(object o, Type t)
{
 ...
}

Double d = 10.0;
foo(d, d.GetType());

foo(d, typeof(Double));

你可以考虑使用泛型。

InsertRow<T>(T data, int columnToSort){
    foreach(var row in listView){
        var value1 = (T)listView.Items[columnToSort].SubItems[columnToSort];
        var value2 = data;
        //From here, it will find where the data object needs to be placed in the ListView and insert it
        if(typeof(T)==typeof(string))
        {
          //do with something wtih data
        }
        else if(typeof(T)==typeof(int))
        {
          //do something else
        }
    }
}

然后调用它,让它自己判断类型。

int i=1;
InsertRow(i,/*column/*);

你可能还想限制T的值,例如,如果你想确保它是一个值类型,where T:struct More

就像这样传递对Column本身的引用:

 protected void DoSort(DataColumn dc)
      {
         string columnName = dc.ColumnName;
         Type type = dc.DataType;
      }

欢呼,CEC