基本上与此问题相同,但在Delphi Prism中:

Cast int to enum in C#

我设法从一个字符串做到这一点:

YourEnum := Enum.Parse(TypeOf(YourEnum), "mystr") as YourEnum


但是我尝试了以下操作,并收到类型不匹配错误:

YourEnum := 3 as YourNum


任何想法将int转换为Enum的语法是什么?

最佳答案

@Robo,将int转换为Enum的语法是

YourEnumVar := YourEnum(3);

要么
YourEnumVar := Object(3) as YourEnum;

看到这个样本
namespace ConsoleAppEnumsDelphiPrism;

interface

type
  Language = (Delphi=1,Delphi_Prism,CBuilder);

  ConsoleApp = class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
var
    MyEnum : Language;
begin
  // String to Enum
  MyEnum := Language(Enum.Parse(typeof(Language), 'Delphi_Prism'));
  Console.WriteLine(MyEnum.ToString());//Print Delphi_Prism

  // Int to Enum
  MyEnum:=Language(2);
  Console.WriteLine(MyEnum.ToString());//Print Delphi_Prism

  // Int to Enum using "as"
  MyEnum:= Object(1) as Language;
  Console.WriteLine(MyEnum.ToString());//Print Delphi

  Console.ReadKey();
end;

end.

10-02 21:39