如何将JObject强制转换为T

时间:2019-01-21 05:32:22

标签: c# generics

我正在尝试为T类型的字段分配一个值,并且代码如下,

JObject jobject = JObject.Parse(strEventData);
EventData = jobject.SelectToken("ChangeSet").ToObject<Client>();

我收到此错误,因为 EventData 的类型为 T ,错误为

无法将类型Client隐式转换为T

这是结构的样子

public struct EventDescriptor<T>
{
    public T EventData;
    public long TimeStamp;
    public ChangeType EventType;

1 个答案:

答案 0 :(得分:2)

您可以使用以下通用方法将T转换为实际类,例如

public static T MyGenericMethod<T>(string strEventData) where T : class
{
    JObject jobject = JObject.Parse(strEventData);
    T result = jobject.SelectToken("ChangeSet").ToObject<T>();
    return result;
}

您可以像使用它

var  EventData = MyGenericMethod<Client>(strEventData);

编辑:

有关与OP进行的聊天的答案已更新。

public struct EventDescriptor<T>
{
    public Guid AggregateId;
    public T EventData;
    public long TimeStamp;
    public ChangeType EventType;
    public int Version;

    public EventDescriptor(Guid id, IEvent eventData)
    {
        AggregateId = id;
        var strEventData = JsonConvert.SerializeObject(eventData, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto });
        EventData = MyGenericMethod(strEventData);
        Version = 1;
        TimeStamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;
        EventType = (ChangeType)Enum.Parse(typeof(ChangeType), eventData.GetType().GetGenericArguments().First().Name);
    }

    public static T MyGenericMethod(string strEventData)
    {
        JObject jobject = JObject.Parse(strEventData);
        T result = jobject.SelectToken("ChangeSet").ToObject<T>();
        return result;
    }
}