简体   繁体   中英

Dynamically determine type to cast to (C#)

My function receives a parameter 'value', of type object. I want to assign it to a member of an object, but the cast doesn't happen implicitly, so I need to specify it explicitly. However, I don't want to actually specify the current type of that member in the object, so I could do this:

positiveOrder.OrderID = (int)value;

But, if business requirements change and OrderIDs are generated and stored in a different way, including a type change to Strings for GUIDS for example, I'll have to come back here and change it, which is undesirable cohesion. I've experimented with various permutations of code like

positiveOrder.OrderID = value as thisOrder.OrderID.GetType();

or

positiveOrder.OrderID = (typeof(thisOrder.OrderID)) value;

But nothing seems to be working. Any ideas on programatically specifying the type to convert to? It can be done at compile time or run time, since the Order class doesn't change.

If positiveOrder.OrderID will always be an integer (even if represented in a string), don't change the member to be anything but an integer. Instead, expose some method that can deal with different source types.

For example:

public void SetOrderID(object value)
{
    this.OrderID = Convert.ToInt32(value);
}

See Convert.ToInt32() .

Something like:

using System.Reflection;

receiver.GetType().GetProperty(propName).SetValue(receiver, value, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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