English 中文(简体)
C#
原标题:C# prevent enum to int conversion
  • 时间:2010-01-14 18:05:11
  •  标签:
  • c#
  • enums

我有一幅大事,列举从外部APIC中恢复的用于我守则的惯用价值。 但是,我不一定知道汇编时间的惯性价值,因此,我有一些法典,在方案启动时把这些价值观hoo上了起来,并将它们储存在一个理论家。

我已经确定了一些转换成/从分类代码转换的推广方法,但这些分类代码与从投放到t的数值相同。 如果另一位方案家用我的头脑,恐怕他们试图把ger子 cast出或从ger里 from出。 而该方案只是沉默地接受坏法典。

是否有办法防止我直言明地转嫁给/from? 如果不是的话,如果有人试图,是否有办法造成一种例外? 或者看看我自己的转换功能? 或改变um的内在价值?

问题回答

你们试图做的是“ir脏”。

采用静态等级,只读值,而不是 en。 之后,你可以初步确定最初用途的数值(或采用静态方法):

public static class Foos
{
    public static readonly int First;
    public static readonly int Second;

    //...

    static Foos()
    {
        //For Example:
        First = DateTime.Now.Day;
        First = DateTime.Now.Month;
    }
}

这样做可能具有意义的另一种方式:在你的节目中界定Enum,在私人方法中将外部的APIC价值描绘到Enum。 换言之,在您的物体模式内,不会暴露出外部的平面体。 例如:

public enum MyEnum { First, Second, Third };

public class MyApiWrapper
{
   private Dictionary<int, int> ExternalToInternal = new Dictionary<int, int>();
   private Dictionary<int, int> InternalToExternal = new Dictionary<int, int>();

   public MyApiWrapper(List<int> externalApiEnumValues)
   {
      foreach (int i = 0; i < externalApiEnumValues.Count; i++)
      {
         ExternalToInternal[externalApiEnumValues[i]] = i;
         InternalToExternal[i] = externalApiEnumValues[i];
      }
   }

   // obviously, your real method for calling the external API 
   // will do more than this.
   public void CallApi()
   {
      CallExternalApi(_EnumValue);
   }

   private MyEnum _ExternalEnumValue;
   public MyEnum EnumValue
   {
      get { return ExternalToInternal[_ExternalEnumValue]; }
      set { _ExternalEnumValue = InternalToExternal[value]; }
   }
}

只要通过这一类产品(一种希望是,你已经把外部消费物价指数的准入归入一个类别),你就可以在申请中自由使用<代码>MyEnum,而不必担心其他方案者对数值有何影响。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签