开发者

How to generically analyze data through code?

开发者 https://www.devze.com 2023-01-31 17:09 出处:网络
I have an XML file that contains a \"script\" of items to check and validate. What it does is reads in a value to check, and if that check is true, it does something. I originally wrote this to work w

I have an XML file that contains a "script" of items to check and validate. What it does is reads in a value to check, and if that check is true, it does something. I originally wrote this to work with just integers, but I realize I need to make it work with more data types.

A sample check is like this...It sees if SomeValue is greater than 20.

<If field="SomeValue" test="@gt" value="20" />

*The field is just some string value. So for a double, the field would be something lik开发者_开发知识库e 55.7.

All I do is do a int.TryParse on the value to see if I can cast the string (SomeValue) to an integer. If I can, I check to see if it is greater than 20. If not, I just assume false on the check.

Does anyone have any suggestions on how I could this with any data type? (i.e. string, double, DateTime) Would Generics work? I have never used them so I dont know if they would be the best solution. Thanks.


The tricky bit is a parse when you don't know the types, but this can be done with TypeDescriptor.GetConverter:

    object knownVal = 21;  //perhaps obtained from reflection
    Type type = typeof(int);
    string text = "20";
    object val = TypeDescriptor.GetConverter(type)
          .ConvertFromInvariantString(text);

    int rel = Comparer.Default.Compare(knownVal, val);

Generics is an option (especially with Comparer<T>.Default.Compare), but generics doesn't mix well with Type values only known at runtime. It can be done (MakeGenericType/MakeGenericMethod), but it is ugly and a bit slow.

To be honest, though: if it was me I would assume there is a small number of types that need handling here, and special-case them.

0

精彩评论

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