11

I read of a useful trick about how you can avoid using the wrong domain data in your code by creating a data type for each domain type you're using. By doing this the compiler will prevent you from accidentally mixing your types.

For example, defining these:

public struct Meter
{
    public int Value;

    public Meter(int value)
    {
        this.Value = value;
    }
}

public struct Second
{
    public int Value;

    public Second(int value)
    {
        this.Value = value;
    }
}

allows me to not mix up meters and seconds because they're separate data types. This is great and I can see how useful it can be. I'm aware you'd still need to define operator overloads to handle any kind of arithmetic with these types, but I'm leaving that out for simplicity.

The problem I'm having with this approach is that in order to use these types I need to use the full constructor every time, like this:

Meter distance = new Meter(5);

Is there any way in C# I can use the same mode of construction that a System.Int32 uses, like this:

Meter distance = 5;

I tried creating an implicit conversion but it seems this would need to be part of the Int32 type, not my custom types. I can't add an Extension Method to Int32 because it would need to be static, so is there any way to do this?

4

1 回答 1

24

You can specify an implicit conversion directly in the structs themselves.

public struct Meter
{
    public int Value;

    public Meter(int value)
    {
        this.Value = value;
    }

    public static implicit operator Meter(int a)
    {
         return new Meter(a);
    }
}

public struct Second
{
    public int Value;

    public Second(int value)
    {
        this.Value = value;
    }

    public static implicit operator Second(int a)
    {
         return new Second(a);
    }
}
于 2012-07-01T00:55:49.147 回答