C#告诉我的界面它只会由struct

时间:2016-04-23 19:26:19

标签: c# class parsing struct interface

我正在尝试实现 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

这些是实施:
(在内部静态Parser类中)

/// <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?

你知道解决方法吗?

1 个答案:

答案 0 :(得分:2)

IParseable通用:

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

然后您可以对IParseableNullableStruct执行相同操作并添加struct constaint:

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