[英]Call generic method on interface implementation only if implemented in C#
[英]C# Tell my interface it is only going to be implemented by struct
我正在嘗試實現IParseable接口以簡化配置讀取:
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);
}
不幸的是,Nullable的通用T參數必須是一個結構。
而且因為我的接口不知道它將由結構實現,所以我無法return IParseableStructNullable?
。
您知道解決方案嗎?
使IParseable
通用:
public interface IParseable<T> {
T Parse(string from);
}
那么您可以對IParseableNullableStruct
做同樣的IParseableNullableStruct
並添加一個struct
約束:
public interface IParseableStruct<T> where T : struct {
T? Parse(string from);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.