0

我有以下对象:

public class ItemChange<T> where T : MyBase
{
public DateTime When { get; set; }
public string Who { get; set; }
public T NewState;
public T OldState;
}

我正在尝试强制转换和实例,ItemChange<T>ItemChange<MyBase>我得到了一个强制转换异常。

无法转换类型的对象。. .

WHat 是将泛型类型转换为其基类的正确方法(假设上面的 where 约束)

4

2 回答 2

3

您不能直接这样做,因为 C# 中的类不支持协变。但是,您可以使用接口来做到这一点:

public interface IItemChange<out T> where T : MyBase
{
    DateTime When { get; set; }
    string Who { get; set; }
    T NewState { get; }
    T OldState { get; }
}

public class ItemChange<T> : IItemChange<T> where T : MyBase
{
    public DateTime When { get; set; }
    public string Who { get; set; }
    public T NewState { get; set; }
    public T OldState { get; set; }
}

然后你可以这样做:

IItemChange<MyBase> base = new ItemChange<MySubclass>();

对于. MySubclass_MyBase

于 2012-11-11T15:35:28.770 回答
0

您需要定义一个显式转换运算符。

using System;
using System.Collections.Generic;
using System.Linq;

namespace brosell
{

public class MyBase
{

}



public class ItemChange<T> where T : MyBase
{
    public DateTime When { get; set; }
    public string Who { get; set; }
    public T NewState;
    public T OldState;

    public static explicit operator ItemChange<MyBase>(ItemChange<T> i)
   {
      return new ItemChange<MyBase> { When = i.When, Who = i.Who, NewState = i.NewState, OldState = i.OldState};
   }

}

public class Sub1: MyBase
{

}

public class Sub2: MyBase
{

}

   public class HelloWorld
   {
    public static void Main(string[] args)
    {
        ItemChange<Sub1> item = new ItemChange<Sub1>();


        ItemChange<MyBase> itemCasted = (ItemChange<MyBase>)item;
        }
   } 
}
于 2012-11-11T15:41:45.547 回答