如何使用T类型在c#中进行类型转换并访问其属性和变量

yog*_*oni 1 c# oop generics polymorphism winforms

IDE:C#.net,Winforms

在我开始请求之前看一下情况:

 public class ParentClass
{

}


public class A : ParentClass
{
    public int A_item1;
    public string A_item2;
    public int CommonVariable;
}

public class B : ParentClass
{
    public int B_item1;
    public string B_item2;
    public int CommonVariable;
}  
Run Code Online (Sandbox Code Playgroud)

现在我从我使用它的地方有form1.cs

  private void button1_Click(object sender, EventArgs e)
    {
        List<ParentClass> lstA = new List<ParentClass>();
        lstA.Add(new A());
        lstA.Add(new A());

        List<ParentClass> lstB = new List<ParentClass>();
        lstA.Add(new B());
        lstA.Add(new B());

        lstA = AssignValue<A>(lstA);

        lstB = AssignValue<B>(lstB);



    }

    private List<ParentClass> AssignValue<T>(List<ParentClass> lstParent)
    {
        foreach (var item in lstParent)
        {
            (item as T).CommonProperty = 5;  // can you tell me how to dynamically type cast here, what ever type is supplied it will type cast accordingly..
        }
        return lstParent;

    }
Run Code Online (Sandbox Code Playgroud)

如您所见,我创建了2个子类A,B和一个ParentClass,

在form1.cs中,我创建了2个类型为Parentclass的List,并在列表1中添加了一个类型对象,在列表2中添加了B类型对象,并将它传递给了一个函数AssignValues

在这里我想自动输入caste,无论用户提供哪种类型T,你能告诉我如何实现这一点.

请不要建议我在parentClass中移动这个变量,因为在我的项目中我不能修改父类,我也不想用switch case解决这个问题.

Eup*_*ric 5

创建一个新界面:

public interface IHasCommonProperty
{
    int CommonProperty {get; set;}
}

public class A : ParentClass, IHasCommonProperty
{
    public int A_item1;
    public string A_item2;
    public int CommonProperty {get ; set; }
}

public class B : ParentClass, IHasCommonProperty
{
    public int B_item1;
    public string B_item2;
    public int CommonProperty {get ; set; }
}  

private List<ParentClass> AssignValue(List<ParentClass> lstParent)
{
    foreach (var item in lstParent)
    {
        var commonInterface = item as IHasCommonProperty;
        if (commonInterface != null)
            commonInterface.CommonProperty = 5;
    }
    return lstParent;
}
Run Code Online (Sandbox Code Playgroud)