开发者

Dynamic Types of fields in .NET

Is it possible to dynamically change the type of the object in a class?

say, I have a Filter class, that specifies a filtering condition for a list of objects of a specific ObjType

Public Class PropertyFilter
  Public Property ObjectType as MyObjectsTypeEnum
  Public Property MainObjectProperty As ??? OBJECT
End Class

Say, when I change the object type, I would like to change also the type of the MainObjectProperty

say, for a Person the main property could be Name (String type) but for a Shpere the main object could be Radius (double type).

I understand that I 开发者_如何学Pythoncould use the generic class, but this is not what I want. Say in the real class I have more that a property that should change when a ObjectType changes, and the user that will use the Filter should have no worry about the MainObjectProperty type, just it should change the Object type - it's all.


That may be a solution for generics. This allows you to have type parameters. Something like this:

Public Class PropertyFilter(Of T)
    Public Property ObjectType
    Public Property MainObjectProperty As T
End Class

That way, when you create a PropertyFilter, you can specify what MainObjectProperty is, like so:

Dim propWithDecimal As New PropertyFilter(Of Decimal)()
Dim propWithString As New PropertyFilter(Of String)()

This isn't dynamic because the type is still known at compile time. You can learn more about generics at MSDN.

EDIT:

Based on the asker's edits:

That sounds like a bit of a quirky design to me. You can't really change the type of a field at runtime - but there are plenty of ways to make it seem like that behavior exists.

You might be able to achieve what you are looking for with dynamic and implementing your own DynamicOjbect, but that'll be some work as well.

The class should decide itself its property type basing of the ObjectType, if you know what I mean.

If that is the case, you will likely have to store it as an object, and make a decision based on which type the object is.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜