【问题标题】:User-defined conversion from an interface to a class [duplicate]用户定义的从接口到类的转换[重复]
【发布时间】:2021-01-10 20:51:55
【问题描述】:

我正在尝试使用用户定义的转换将List<ICommonKline> 转换为List<Candle>,但由于 ICommonKline 是一个接口,因此我无法这样做。

不允许用户定义的与接口之间的转换

我该怎么做?

这就是我想要完成的:

List<ICommonKline> smt = (await api.GetCandlesAsync("TRXUSDT", TimeSpan.FromHours(1), limit: 500)).SkipLast(1).ToList();
List<Candle> smt2 = smt.Cast<Candle>().ToList(); // System.InvalidCastException: 'Unable to cast object of type 'Binance.Net.Objects.Spot.MarketData.BinanceSpotKline' to type 'NewBot.Core.Indicators.Candle'.'

代码:

public interface ICommonKline
{
    decimal CommonHigh { get; }
    decimal CommonLow { get; }
    decimal CommonOpen { get; }
    decimal CommonClose { get; }
}

public class Candle
{
    public decimal High { get; set; }
    public decimal Low { get; set; }
    public decimal Open { get; set; }
    public decimal Close { get; set; }
    public decimal Volume { get; set; }
    public DateTime OpenTime { get; set; }
    public DateTime CloseTime { get; set; }

    public static explicit operator Candle(ICommonKline candle) // error CS0552: 'Candle.explicit operator Candle(ICommonKline)': user-defined conversions to or from an interface are not allowed
    {
        var c = new Candle();



        return c;
    }
}

【问题讨论】:

  • 抱歉我的解决方案不起作用,请参阅 (stackoverflow.com/questions/2433204/…)。但是您可以将代码从explicit 转移到Select() lambda
  • 您正在尝试将 ICommonKline 转换为 Candle,而不是强制转换,因为 Candle 不是 ICommonKline,所以不要使用强制转换或显式运算符。只需编写一个转换器或 ConvertTo 方法。

标签: c# type-conversion


【解决方案1】:

似乎这是唯一的好方法。

var candles = new List<ICommonKline>();

...

return candles.Select(x => new Candle
{
    High = x.CommonHigh,
    Low = x.CommonLow,
    Open = x.CommonOpen,
    Close = x.CommonClose
}).ToList();

【讨论】:

    【解决方案2】:

    使用构造函数代替操作符

    public class Candle
    {
        public decimal High { get; set; }
        public decimal Low { get; set; }
        public decimal Open { get; set; }
        public decimal Close { get; set; }
        public decimal Volume { get; set; }
        public DateTime OpenTime { get; set; }
        public DateTime CloseTime { get; set; }
    
        public Candle(ICommonKline candle)
        {
             var c = new Candle();
             // ...
        }
    
        public Candle()
        {
        }
    }
    

    然后你就可以进行转换了

    List<Candle> smt2 = smt.Select(item => new Candle(item)).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多