如何将对象转换为键入c#

时间:2015-11-06 16:31:51

标签: c# types casting

我的类型变量很少

Int16[], Double[]

我把它们推到像这样的功能

Int16[] variable = ...;
Func(variable);

Double[] variable = ...;
Func(variable);

///////////////////////////////
private void Func(Object input)
{
    var data = (input.GetType())input; ?????

    //some actions with data
}

在这种情况下

var data = input.ToString();

数据成为内容为“System.Int16 []”或“System.Double []”的字符串

如何在func中输入我的数据变为Int16 []或Double []类型的输入对象,即数据应该是Int16 []或Double []的数组,或者我在func中推送的任何类型我可以为示例此操作:

for(int i = 0; i < data.length; ++i)
{
    data[i] = data[i] * 5;
}

4 个答案:

答案 0 :(得分:2)

这里有几个选项,首先你可以使用通用功能:

    function remDeskId(){
    userObject = $dropObject.find('div.dragTest');
    userObjectChange = 'REMOVESEAT';
    userObjectID = userObject.attr('data-info');
    userObjectDeskID = userObject.attr('data-id');
    userObjectDeskIDVal = 0;
    $('form#logForm').append("<span class='close' style='display:none' id='"+userObjectID+"' desk='"+userObjectDeskID+"' deskval='"+userObjectDeskIDVal+"' changeType='"+userObjectChange+"'></span>");

    userObject.attr({"data-id":""}); //remove desk number for new user location
    userObject.appendTo('#userPool');

}

$('#submit').click(function(){
        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        //var formData = {

       // };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'seatingProcess.php', // the url where we want to POST
            data        : $('#logForm').serialize(), // our data object

        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data); 

                // here we will handle errors and validation messages
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

或者你可以这样做:

private void MyFunction<T>(T[] values)
{
    for (int i = 0; i < values.Length; i++)
    {
        //Here is where the issue is, you can't constrain T to a value type that
        //defines mathematical operators, so the best you can do is dynamic:
        values[i] = (dynamic)values[i] * 5;
    }
}

我觉得哪个更脏。无论哪种方式,您应该在这些函数的顶部进行某种类型检查,以验证传入的参数是否为数字数组类型,然后才假定它正在运行代码。

您发布的行:

private void MyFunction(object values)
{
    //Assume that object is an array, and go from there
    for (int i = 0; i < ((dynamic)values).Length; i++)
    {
        ((dynamic)values)[i] = ((dynamic)values)[i] * 5;
    }
}

显然不起作用,因为var data = (input.GetType())input; 返回GetType(),它在编译时没有用类型的名称替换自己,所以它不是有效的强制转换

答案 1 :(得分:1)

您可以Convert.ChangeType看到以下内容:

var valueType = typeof (TValue);
valueType = Nullable.GetUnderlyingType(valueType) ??  valueType;

var value = (TValue) Convert.ChangeType(environmentValue, valueType);

答案 2 :(得分:0)

我认为你想要像这样的Type参数:

private void Func<T>(T[] input)
    {
        var data = input; //Unnecessary but since you used it, so did I.
        // Now you can perform actions with data.
        // Call this function like this:
        // Func<Double>(variable) or Func<Int16>(variable) or any other type you want.
    }

答案 3 :(得分:0)

  

如何投射输入对象,我的数据成为Int16 []或类型的类型   在函数中加倍[],

如果使用数组的操作占主导地位,我会在接口中封装常用的算术运算,以便从泛型函数中使用它。

var int16Data = new short[] {1, 2, 3, 4};
MyFunc(int16Data);

var doubleData = new double[] {1.0, 2.0, 3.0, 4.0};
MyFunc(doubleData);

用法:

class DoubleArithmeticOperation: IArithmeticOperation<Double>
{
    public void Shift(double[] left, object value) 
    { 
       double v = Convert.ToDouble(value);
       for(int i = 0; i < left.Length, ++i} {left[i] += v};
    }

    public void Scale(double[] left, object value) 
    {
        double v = Convert.ToDouble(value);
        for(int i = 0; i < left.Length, ++i} {left[i] *= v};
    }
}


class Int16ArithmeticOperation: IArithmeticOperation<Int16>
{
    public void Shift(short[] left, object value) 
    { 
        short v = Convert.ToInt16(value); 
        for(int i = 0; i < left.Length, ++i} {left[i] += v};
    }

    public void Scale(short[] left, object value) 
    {
        short v = Convert.ToInt16(value); 
        for(int i = 0; i < left.Length, ++i} {left[i] *= v};
    }
}

可能的实施:

{{1}}