简体   繁体   English

转换对象类型的最快方法是什么

[英]What is the fastest way to convert an Object type

I have a class that returns an object type to a variable. 我有一个将对象类型返回给变量的类。 The variable Must know what the real type is when operations are performed on it: 变量必须对其执行操作时知道真实类型是什么:

public object Data 
    {
        get
        {
            switch (CriteriaID)
            {
                case (int)matrix2.enums.NodeTypeEnums.Enums.MultiLineText:
                    return (string)_Data;
                case (int)matrix2.enums.NodeTypeEnums.Enums.SingleLineText:
                    return (string)_Data;
                case (int)matrix2.enums.NodeTypeEnums.Enums.Number:
                    int temp = 0;
                    return int.TryParse((string)_Data, out temp) ? (int?)temp : null;
                case (int)matrix2.enums.NodeTypeEnums.Enums.Price:
                    decimal temp1 = 0;
                    return decimal.TryParse((string)_Data, out temp1) ? (decimal?)temp1 : null;
                case (int)matrix2.enums.NodeTypeEnums.Enums.PullDown:
                    return (string)_Data;
                case (int)matrix2.enums.NodeTypeEnums.Enums.Checkbox:
                    bool temp2 = false;
                    return bool.TryParse((string)_Data, out temp2) ? (bool?)temp2 : null;
                case (int)matrix2.enums.NodeTypeEnums.Enums.Date:
                    DateTime temp3 = DateTime.MinValue;
                    return DateTime.TryParse((string)_Data, out temp3) ? ((DateTime?)temp3).Value.ToString("MM/dd/yyyy") : null;
                case (int)matrix2.enums.NodeTypeEnums.Enums.Link:
                    return (string)_Data;
                case (int)matrix2.enums.NodeTypeEnums.Enums.Image:
                    return (string)_Data;
                default:
                    return (string)_Data;
            }
        }
        set
        {
            _Data = value;   
        }
    }

The data property is used like this: data属性的用法如下:

temp.Count() > 0 ? temp.FirstOrDefault().Data : " "

Using it like this works but I am not sure if this is the best implementation and/or the most efficient. 像这样使用它是可行的,但是我不确定这是否是最佳实现和/或最有效。 Is their a better way to do this? 他们是这样做的更好方法吗?

To be honest, seeing as your dealing with a finite number of possible results, you might as well stick to using a switch statement. 老实说,在处理有限数量的可能结果时,您最好还是坚持使用switch语句。 What I would do, is change a lot of what you are doing... 我会做的就是改变您正在做的很多事情...

Firstly, don't put any complex operations with getters or setters. 首先,不要对getter或setter进行任何复杂的操作。 You should push these out to a seperate method: 您应该将它们推出一个单独的方法:

public object Data
{
  get
  {
    return FormatData(_Data);
  }
}

Secondly, you don't need to cast in your case blocks: 其次,您无需强制使用case块:

case (int)matrix2.enums.NodeTypeEnums.Enums.MultiLineText:

Thirdly, 第三,

temp.Count() > 0 ? temp.FirstOrDefault().Data : " "

...there are a few issues here to, for instance: ...这里有一些问题,例如:

temp.Count() > 0

...will cause the entire enumerable to be enumerated, its much more efficient to do: ...将导致整个枚举被枚举,这样做的效率要高得多:

temp.Any()

...as it will return after it encounters the first element, next: ...因为它将在遇到第一个元素next之后返回:

temp.FirstOrDefault().Data

if you are calling .Count() > 0 (or now hopefully .Any() ), you can change this to .First() , as you've already established that there must be an instance for it to hit this logic path. 如果要调用.Count() > 0 (或现在有希望.Any()您可以将其更改为.First()因为你已经确定,必须有一个实例为它打这个逻辑路径。

temp.FirstOrDefault().Data : "&nbsp";

Because your method potentially returns types other than string, the result of the complete tertiary operation can only be assigned to Object, because the compiler won't know which argument type it can be assigned to....imagine you are returning an Int32 or a String , which one? 因为您的方法可能返回字符串以外的类型,所以只能将完整的三次操作的结果分配给Object,因为编译器不知道可以将其分配给哪种参数类型。...想象您正在返回Int32或一个String ,哪个?

UPDATE Now I think about it, a really important change you should make is simply: 更新现在我考虑一下,您应该做的一个非常重要的更改就是:

public object Data { get; set;}

The property should really just return the raw data. 该属性实际上应该只返回原始数据。 It should be outside the problem domain of the model that you present the data (and hence convert it into other types). 您应该在模型的问题域之外显示数据(并因此将其转换为其他类型)。

It looks like you are essentially writing the object out to html, so why all the work to do with formatting it? 看起来您实际上是将对象写成html,那么为什么要进行格式化工作呢? For the most part you can use .ToString() to get the string representation of the object: 在大多数情况下,您可以使用.ToString()获取对象的字符串表示形式:

temp.Any() ? temp.First().Data.ToString() : "nbsp;"

Assuming that your origin type is compatible with the destination type, you can do something like this: 假设您的原始类型与目标类型兼容,则可以执行以下操作:

public T ConvertValue<T>(object value)
{
    return (T)Convert.ChangeType(value, typeof(T), null);
}

(Or if you have the Convert.ChangeType overload that does not require the IFormatProvider) (或者,如果您具有不需要IFormatProvider的Convert.ChangeType重载)

public T ConvertValue<T>(object value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

And then consume it by doing 然后通过做来消耗它

int myValueConvertedToInt = ConvertValue<int>("12345");

However, if the types are not compatiable, ie, you try something like 但是,如果类型不兼容,即尝试

int myValueConvertedToInt = ConvertValue<int>("XXX");

It will throw. 它会抛出。 Therefore, you will want to have strong validation in place on the properties you will attempt to convert. 因此,您将要对要转换的属性进行充分的验证。 I'm partial to the System.ComponentModel.DataAnnotations attributes for attaching validation requirements to properties. 我偏爱System.ComponentModel.DataAnnotations属性,用于将验证要求附加到属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM