gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:30 25 4
gpt4 key购买 nike

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;
}

现在我从我使用它的地方得到了 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;

}

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

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

这里我想自动键入它,无论用户提供类型 T,你能告诉我如何实现这一点。

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

最佳答案

创建一个新界面:

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;
}

关于c# - 如何在 C# 中使用 T 类型进行类型转换并访问其属性和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28186689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com