开发者

Sending DataType As An Argument?

I'm trying to write a method that uses the following two arguments:

ColumnToSort
ColumnType

The reason I want to be able to do this is interpreting two things as a string can give a different result than comparing the same two things as a number. For example

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

So basically, I want to be able to send double or string datatype as a method argument, but I don't know how to do this, but it seems like something that should be possible in C#.

Addendum:

What I want my method to look like:

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
    }
}

How it will be called:

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. 


You can use Type as parameter type. like this

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

and call

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

or

foo(d, typeof(Double));


You might consider using generics.

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
        }
    }
}

Then call it, and let it figure out the type by itself.

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

You may also want to restrict what T can be, for instance if you want to make sure it's a value type, where T:struct More


Just pass a reference to the Column itself like this:

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

Cheers, CEC

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜