为什么C#不包含IParsable <T>或ITryParsable <T>?

dav*_*v_i 3 c#

编辑:显然这是不可能的,因为C#不允许接口中的静态方法.

显然,为您自己的解决方案实现以下接口会相当简单

public interface IParsable<T>
{
    T Parse(string s);
}

public interface ITryParsable<T> : IParsable<T>
{
    bool TryParse(string s, out T output);
}
Run Code Online (Sandbox Code Playgroud)

已经写解析未知类型化的用户输入数据的各种方式,我会发现有int,decimal等,等实现一个版本,这些接口必不可少的.

对我而言,包含在System命名空间中似乎是一件相当明显的事情.

显然事实并非如此.那么查看类是否"实现"这些接口的最佳方法是什么?

通过Duck Typing检查方法是否存在似乎是一个明智的选择,但是反射并不是非常高效.

kb4*_*000 6

.NET 7 添加了IParsable。它现在用于所有这些类型:

System.Byte
System.Char
System.DateOnly
System.DateTime
System.DateTimeOffset
System.Decimal
System.Double
System.Guid
System.Half
System.Int128
System.Int16
System.Int32
System.Int64
System.IntPtr
System.ISpanParsable<TSelf>
System.Numerics.BigInteger
System.Numerics.Complex
System.Numerics.IBinaryFloatingPointIeee754<TSelf>
System.Numerics.IBinaryInteger<TSelf>
System.Numerics.IBinaryNumber<TSelf>
System.Numerics.IExponentialFunctions<TSelf>
System.Numerics.IFloatingPoint<TSelf>
System.Numerics.IFloatingPointConstants<TSelf>
System.Numerics.IFloatingPointIeee754<TSelf>
System.Numerics.IHyperbolicFunctions<TSelf>
System.Numerics.ILogarithmicFunctions<TSelf>
System.Numerics.INumber<TSelf>
System.Numerics.INumberBase<TSelf>
System.Numerics.IPowerFunctions<TSelf>
System.Numerics.IRootFunctions<TSelf>
System.Numerics.ISignedNumber<TSelf>
System.Numerics.ITrigonometricFunctions<TSelf>
System.Numerics.IUnsignedNumber<TSelf>
System.Runtime.InteropServices.NFloat
System.SByte
System.Single
System.TimeOnly
System.TimeSpan
System.UInt128
System.UInt16
System.UInt32
System.UInt64
System.UIntPtr
Run Code Online (Sandbox Code Playgroud)


Mat*_*vey 5

由于C#不支持静态接口,因此您必须拥有该对象的实例才能调用parse方法.你会得到这样的东西:

var a = new int().Parse<int>("123");
var b = 123.Parse("567");
Run Code Online (Sandbox Code Playgroud)

或者通过这种TryParse方法,事情变得更加奇怪:

int x;
if (x.TryParse("456", out x))
    // trippy... now imagine that x is a reference type...
Run Code Online (Sandbox Code Playgroud)