2016-04-23 51 views
0

我想實現的IParseable界面來簡化配置讀來實現:C#告訴我的接口它只會通過結構

public interface IParseable { 
    IParseable Parse(string From); 
} 

要分析我已經建立了這些字符串擴展方法的字符串:

public static T ToIParseableStruct<T>(this string Me) where T : struct, IParseable 
    => Parser.IParseableStructFromString<T>(Me); //Never returns null 

public static T ToIParseableClass<T>(this string Me) where T : class, IParseable, new() 
    => Parser.IParseableClassFromString<T>(Me); //Could return null 

這些是實現:
(內部的內部靜態分析器類)

/// <exception cref="FormatException">Thrown when <paramref name="Value"/> could not be parsed. (See <see cref="IParseable.Parse(string)"/>)</exception> 
public static T IParseableStructFromString<T>(string Value) where T : struct, IParseable { 
    T result = new T(); 
    try { 
     return (T)result.Parse(Value); 
    } catch(Exception ex) { 
     return ThrowFormatException<T>(Value, ex); //Ignore this 
    } 
} 

/// <exception cref="FormatException">Thrown when <paramref name="Value"/> could not be parsed. (See <see cref="IParseable.Parse(string)"/>)</exception> 
public static T IParseableClassFromString<T>(string Value) where T : class, IParseable, new() { 
    T result = new T(); 
    try { 
     return (T)result.Parse(Value); 
    } catch(Exception ex) { 
     return ThrowFormatException<T>(Value, ex); //Ignore this 
    } 
} 

到目前爲止太棒了!
我也想允許解析一個字符串爲可空結構。
這是我的嘗試:

public interface IParseableStructNullable { 
    IParseableStructNullable? Parse(string From); 
} 

不幸的是可空的泛型T參數必須是一個結構。
而且因爲我的界面不知道它將由一個結構實現我不能return IParseableStructNullable?

你知道這個解決方案嗎?

回答

2

IParseable通用:

public interface IParseable<T> { 
    T Parse(string from); 
} 

,那麼你可以爲IParseableNullableStruct做同樣的,並添加一個struct constaint:

public interface IParseableStruct<T> where T : struct { 
    T? Parse(string from); 
} 
+0

你知道如何簡單,它可能是瞬間......謝謝李:) –

相關問題