【发布时间】: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