如何创建通常使用泛型方法生成的类的实例?

时间:2021-04-13 10:22:06

标签: c# activator

我正在实现一个库,我必须在其中进行一些转换才能获取类的实例,从 .dll 的文档中我们可以找到一个工作代码示例

df <- df %>%
  mutate(across(where(is.factor), ~fct_infreq(fct_drop(.x))))

我想实现一个看起来像这样的方法:

   public void Example()
    {
        DeviceItem deviceItem = ...;
        GsdDeviceItem gsdDeviceItem =((IEngineeringServiceProvider)deviceItem).GetService<GsdDeviceItem>();             

        var attributeNames = new[] { "TypeName", "Author", "Comment" };

        foreach (var attributeName in attributeNames)
        {
            object attributeValue =
                ((IEngineeringObject)gsdDeviceItem).GetAttribute(attributeName);
        }
    }    
        

我收到错误 CS0118 'serviceType' is a variable but is used like a type, 如果有人能帮我,那就太好了

1 个答案:

答案 0 :(得分:0)

如果 IEngineeringServiceProvider 继承自 IServiceProvider,请使用:

var service = Activator.CreateInstance(((IEngineeringServiceProvider)item).GetService(serviceType));

就这些

相关问题