SORU
20 HAZİRAN 2011, PAZARTESİ


Neden döküm geçersiz numaralandırma değeri int mi istisna YOK?

Eğer böyle bir sıralama yaparsam:

enum Beer
{
    Bud = 10,
    Stella = 20,
    Unknown
}

Neden Beer Bir tür için bu değerlerin dışında int bir döküm zaman, bir özel durum değil mi?

Örneğin aşağıdaki kod bir özel durum yok, çıktılar '50' konsola:

int i = 50;
var b = (Beer) i;

Console.WriteLine(b.ToString());

Bu tuhaf buluyorum...kimseye açıklamak miyim?

CEVAP
20 HAZİRAN 2011, PAZARTESİ


Confusion with parsing an Enum alınan

Bunu yaratan insanlar adına bir karar oldu .NET. Bir numaralama aslında bu değer türleri için geçerli olan herhangi bir değer olabilir başka bir değer yazın (int, short, byte, vb), ve böylece tarafından desteklenmektedir.

Ben şahsen bu işler böyle bir hayranı değilim, yardımcı yöntemleri bir dizi yaptım:

/// <summary>
/// Utility methods for enum values. This static type will fail to initialize 
/// (throwing a <see cref="TypeInitializationException"/>) if
/// you try to provide a value that is not an enum.
/// </summary>
/// <typeparam name="T">An enum type. </typeparam>
public static class EnumUtil<T>
    where T : struct, IConvertible // Try to get as much of a static check as we can.
{
    // The .NET framework doesn't provide a compile-checked
    // way to ensure that a type is an enum, so we have to check when the type
    // is statically invoked.
    static EnumUtil()
    {
        // Throw Exception on static initialization if the given type isn't an enum.
        Require.That(typeof (T).IsEnum, () => typeof(T).FullName   " is not an enum type.");
    }

    /// <summary>
    /// In the .NET Framework, objects can be cast to enum values which are not
    /// defined for their type. This method provides a simple fail-fast check
    /// that the enum value is defined, and creates a cast at the same time.
    /// Cast the given value as the given enum type.
    /// Throw an exception if the value is not defined for the given enum type.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="enumValue"></param>
    /// <exception cref="InvalidCastException">
    /// If the given value is not a defined value of the enum type.
    /// </exception>
    /// <returns></returns>
    public static T DefinedCast(object enumValue)

    {
        if (!System.Enum.IsDefined(typeof(T), enumValue))
            throw new InvalidCastException(enumValue   " is not a defined value for enum type "  
                                           typeof (T).FullName);
        return (T) enumValue;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="enumValue"></param>
    /// <returns></returns>
    public static T Parse(string enumValue)
    {
        var parsedValue = (T)System.Enum.Parse(typeof (T), enumValue);
        //Require that the parsed value is defined
        Require.That(parsedValue.IsDefined(), 
            () => new ArgumentException(string.Format("{0} is not a defined value for enum type {1}", 
                enumValue, typeof(T).FullName)));
        return parsedValue;
    }

    public static bool IsDefined(T enumValue)
    {
        return System.Enum.IsDefined(typeof (T), enumValue);
    }

}

Bu şekilde diyebilirim ki

if(!sEnum.IsDefined()) throw new Exception(...);

... ya da:

EnumUtil<Stooge>.Parse(s); // throws an exception if s is not a defined value.

Edit

Açıklama yukarıda verilen dışında, fark var .NET sürüm Numaralama C-ilham daha fazla desen Java esinlenen bir daha izler. Bu sayede ikili desenler "bayrak" numaralama değeri aktif. belirli bir olup olmadığını belirlemek için kullanabileceğiniz "Bit Flag" enums için yapar Eğer bayraklar (15*,* 16 *yani*) her olası birleşimini tanımlamak için olsaydı, bu son derece sıkıcı olurdu. Yani tanımsız numaralandırma değerleri kullanmak için kapasitesine sahip gerçekten kullanışlı olabilir. Sadece hileler bu tür kaldıraç yok numaralama türleri başarısız-hızlı bir davranış, istediğiniz zaman küçük bir ekstra çalışma gerektirir.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:
C#

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Liberator

    Liberator

    14 EYLÜL 2007
  • Lin Steven

    Lin Steven

    17 EKİM 2006
  • Top Gear

    Top Gear

    27 Mart 2006