将C#泛型类型作为参数传递 [英] Pass C# generic type as a parameter

查看:1498
本文介绍了将C#泛型类型作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个声明为

public interface ISomething<T> where T : class

在界面的某处,我有一个成员声明为

and somewhere in the interface I have a member declared as

[JsonProperty("someProperty")]
[JsonConverter(typeof(ConcreteTypeConverter<List<T>>))]
List<T> SomePropertyList{ get; set; }

我在ConcreteTypeConverter<List<T>>上收到一条错误消息,说它不能使用类型(T)作为参数.我的ConcreteTypeConverter类使用类型T并返回JSON反序列化所需的T的具体实现.这里的情况是T可以有大约20种不同的类型,但我想避免使用20个这样的接口-这就是为什么我选择了通用接口.

I get an error on ConcreteTypeConverter<List<T>> saying it cannot use a type (T) as an argument. My ConcreteTypeConverter class takes a type T and returns a concrete implementation of T which is needed for JSON deserialization.The scenario here is that T can have about 20 different types.But I would like to avoid having 20 such interfaces - that's why I opted for a generic interface.

用法类似于

ISomething<SomeType> variable = new Something<SomeType>();
var list = variable.SomePropertyList;

其中SomeType是T的实际实现.在这种情况下是否可以使用泛型?

where SomeType is the actual implementation of the T. Is there any way to use generics in such a situation?

我的ConcreteConverterClass继承自JsonConverter(使用Newtonsoft.Json):

My ConcreteConverterClass derives from JsonConverter (using Newtonsoft.Json):

public class ConcreteTypeConverter<TConcrete> : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return serializer.Deserialize<TConcrete>(reader);
        }
    }

我的确切错误是:

Attribute Argument cannot use type parameters

推荐答案

如果SomePropertyList不是具体类型,例如,

You only need the ConcreteTypeConverter if SomePropertyList is not a concrete type, e.g.

[JsonProperty("someProperty")]
[JsonConverter(typeof(ConcreteTypeConverter<List<T>>))]
IList<T> SomePropertyList{ get; set; }

如果这不是问题,只需将您的属性声明更改为

If this is not an issue, just change your property declaration to

[JsonProperty("someProperty")]
List<T> SomePropertyList{ get; set; }

这篇关于将C#泛型类型作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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