【问题标题】:How to convert properly an object to KeyValuePair.Key?如何将对象正确转换为 KeyValuePair.Key?
【发布时间】:2021-10-14 15:10:15
【问题描述】:

我正在努力将object 转换为KeyValuePair.Key。在我的方法中,我有签名:

public EstimatorChain<RegressionPredictionTransformer<PoissonRegressionModelParameters>> GetRegressionPipeline(MLContext context, KeyValuePair<Type, object> algorithm)

铸造:(algorithm.Key)algorithm.Valuealgorithm.Value as algorithm.Key 会抛出异常:

算法是一个变量,但用作类型

如何正确转换为Key 类型?假设ValueLbfgsPoissonRegressionTrainer something = new LbfgsPoissonRegressionTrainer();

【问题讨论】:

  • 这是因为即使该变量的类型为Type,您也无法将某些内容强制转换为变量。如果您真的想要这样做,那么您需要使用reflection 来完成您想要在object 上执行的所有操作
  • 我还是不明白,我应该如何反思Key,假设例如Keytypeof(LbfgsPoissonRegressionTrainer),或者objectLbfgsPoissonRegressionTrainer something = new LbfgsPoissonRegressionTrainer()
  • 实际问题是什么?您是否在尝试调用方法并且无法提供参数?还是您想使用 keyValuePair 的键属性来做某事?

标签: c# dictionary casting type-conversion key-value


【解决方案1】:

我的问题有两种解决方案。

首先只是对EstimatorChain&lt;RegressionPredictionTransformer&lt;PoissonRegressionModelParameters&gt;&gt;类型进行强制转换:

(IEstimator<RegressionPredictionTransformer<PoissonRegressionModelParameters>>)algorithm.Value

另一种是使用var value = Convert.ChangeType(item.Value, item.Key);:

.Append((dynamic)Convert.ChangeType(algorithm.Value, algorithm.Key));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2012-05-14
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多