开发者

Dynamic conversion c#

I know it has been asked seve开发者_开发技巧ral times but I'm having very hard time understanding the <T> concept.

I'm working on a custom GridView and I want to set the Cell.Value property upon CellUpdate event. the problem is that in most cases I will have to take a string from the cell's control input while I have no idea how to 'dynamically' convert (in elegant way) this String to the original object which in this case is represented in _Value as object.

Hope any of this make some sense, thank you.


Generic (<T>) and Dynamic are two opposite concepts. Generics should be known at compile-time and dynamic are resolved at runtime. So if you know the type (<T>) dynamically only at runtime you cannot invoke a generic method unless you use reflection.

Depending on your specific requirements and code you are dealing with there might be different solutions.


Generics and reflections are very hard together and are not recommended to use. If you get to a point where you want to use both together, it is usually a bad design to begin with. Even if it is not a bad design, consider alternatives which would not require you to take this course of action.

I had some experience with generics and reflection and I don't recommend it one bit.


I'm assuming your CellUpdate event has the equivalent of an (Object sender) ? You should be able to do a cast of the sender to your control and use the properties from that point. It's hard to provide an exact example since I don't know how your type is set up but it could be something similar to ((GridViewCell)sender).Text; There are probably many ways to do this but it's going to depend a lot upon your specific implementation.


There is no easy, automatic way to do it. You can relatively easily convert between primitives (i.e. types that implement IConvertable), using Convert.ChangeType(). But otherwise you're on your own.

For example, this is a crude, but possible way of doing it:

object v = myCell.Value;
if(v is int)
{
    int vInt = (int)v;
    // ...
}
else if(v is string)
{
    string vStr = (string)v;
    // ...
}
else if(v is MyClass)
{
    MyClass vMyClass = (MyClass)v;
    // ...
}
// ...

Note that in case of reference types, it's preferable to use as and then check for null - I didn't use it above because it leads to ugly code, a lot of local variables, and I prefer to avoid that and I rather pay the performance penalty.


You could use TypeConveters, either the built-in for System types, or write your own for custom types, e.g:

 TypeConverter converter = TypeDescriptor.GetConverter(type);
 if (converter.CanConvertFrom(typeof(string)))...

Take a look at my answer to another StackOverflow question

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜