简体   繁体   中英

Cannot convert string to enum

I need to make an adapter class.

trip.Resource is an enum named ModalityResource.

transportOrderTrip.ModalityResource is a string.

if(Enum.IsDefined(typeof(ModalityResource), transportOrderTrip.ModalityResource))
    trip.Resource = Enum.Parse(typeof(ModalityResource), transportOrderTrip.ModalityResource, true);

Possible values for ModalityResource here:

 public enum ModalityResource { NONE, CHASSIS, TRAILER }

The error i get is this one: Cannot implicitly convert type 'object' to 'ModalityResource'. Anyone might know what is wrong?

Edit: Never mind, was bit confused.

  trip.Resource = (ModalityResource) Enum.Parse(typeof (Shared.Interfaces.ModalityResource), transportOrderTrip.ModalityResource, true);

You've to cast the result of Enum.Parse as ModalityResource . In .NET 4 or newer you can also use the generic overloads of the function.

trip.Resource = (ModalityResource)Enum.Parse(typeof(ModalityResource), transportOrderTrip.ModalityResource, true);

See also

http://msdn.microsoft.com/en-us/library/dd783499.aspx

You need as cast.

Enum.Parse method returns object

change your code to following

(ModalityResource)Enum.Parse(typeof(ModalityResource), transportOrderTrip.ModalityResource, true);

Well you would need to cast it to the required Enum type as the return type is object

(ModalityResource) Enum.Parse(typeof(ModalityResource), 
                             transportOrderTrip.ModalityResource, true);

On Why object is returned instead of an enum value

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