用C#中的通用方法编译错误 [英] Compile Error With Generic Method in C#

查看:59
本文介绍了用C#中的通用方法编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现如果将IMetadataType对象强制转换为TMetadata类型,则可以对其进行编译.为什么我需要这样做?

I found out that I can get it to compile if I cast the IMetadataType object to the TMetadata type. Why do I need to do this?

编辑#2:值"属性是< TMetadata,TData>类型的.NET字典.

EDIT #2: The "Values" property is a .NET dictionary of type <TMetadata, TData>.

我有这个通用方法:

private void FillMetadata<TMetadata, TData>
    (Metadata<TMetadata, TData> oMetadata) where TMetadata : IMetadataType
{
    IMetadataType o;
    oMetadata.Values.Add(o, (TData)(object)GetValue());
}

我剥离了实现以简化它(我实际上使用的是真实对象,而不是此处声明的IMetadataType).

I have stripped the implementation to simplify it (I actually use a real object, not the IMetadataType declared here).

我的问题是,为什么不编译?编译错误发生在Add()方法上:无法从'IMetadataType'转换为'TMetadata'."这不是方法中的"where"子句用于什么吗?

My question is, why doesn't this compile? The compile error is on the Add() method: "cannot convert from 'IMetadataType' to 'TMetadata'." Isn't that what the "where" clause on the method is for?

我想念什么?

推荐答案

where TMetadata : IMetadataType是对通用类型参数TMetadata的约束,称其应从IMetadataType派生.由于oMetadata仅将TMetadataTData作为要使用的类型,因此您必须在方法主体中使用它们.这应该起作用:

The where TMetadata : IMetadataType is a constraint for the generic type parameter TMetadata saying it should derive from IMetadataType. Since oMetadata knows only TMetadata and TData as types to work with, you have to use them in your methods body. This should work:

private void FillMetadata<TMetadata, TData>(Metadata<TMetadata, TData> oMetadata) 
    where TMetadata : IMetadataType
{
    TMetadata o;
    oMetadata.Values.Add(o, (TData)(object)GetValue());
} 

这篇关于用C#中的通用方法编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆