Generate Cast type dynamically in C#

左心房为你撑大大i 提交于 2019-12-13 17:27:06

问题


Please I have a class in c# whose main function is to return the types and objects as dictionary Over a service .

Is it possible to cast the Object sents over the WCF service in the front end.

I.e using reflection to get the type of an object from the types.ToString() and using the type to cast the objects.

NB the Class that returns the dictionary and my frontend are in different projects so different Namespaces:

Type repType = typeof(List <>).MakeGenericType(Type.GetType(EntityandTypes[entity]));
object rep = Assembly.GetAssembly(repType).CreateInstance(repType.FullName);
grdResult.ItemsSource = 
    e.Result.ToList().Cast<typeof(Type.GetType(EntityandTypes[entity]))>();

Note : EntityandTypes is a dictionary that contains Object and Their types.


回答1:


What would you want to do with the cast values? Casts usually make a difference at compile-time whereas you're asking for something at execution-time.

If you can explain how you'd want to use this, we can probably help you design around it.




回答2:


What sort of types are we talking about? classes? And what type of service is it?

If it is WCF, one option is to use type-sharing to use the same type at each end, but this abuses SOA a little bit. You can't cast a class to a very different type, but you can project into a different class. Various approaches for this are discussed here:

How to copy value from class X to class Y with the same property name in c#?



来源:https://stackoverflow.com/questions/1165275/generate-cast-type-dynamically-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!