使用函数根据传递的类型创建类的实例
本文关键字:类型 创建 实例 函数 | 更新日期: 2023-09-27 18:29:00
我有这个方法:
internal static void AssignNewArrayItem(ref Xml.CLASSNAME[] Items, Xml.CLASSNAME Item)
{
if (Items != null)
{
Array.Resize(ref Items, Items.Length + 1);
Items[Items.Length - 1] = Item;
}
else
Items = new Xml.CLASSNAME[] { Item };
}
目前,我有大约10个重载版本,其中CLASSNAME
不同,但它们都做完全相同的事情。有没有什么方法可以让CLASSNAME
作为通用对象,并强制转换vars以获得相同的结果?
如果我也以错误的方式处理这件事,我愿意接受其他建议,以获得同样的结果。
internal static void AssignNewArrayItem<T>(ref T[] Items, T Item)
{
if (Items != null)
{
Array.Resize(ref Items, Items.Length + 1);
Items[Items.Length - 1] = Item;
}
else
Items = new T[] { Item };
}
你试过这个吗:
internal static void AssignNewArrayItem<T>(ref T[] Items, T Item)
{
if (Items != null)
{
Array.Resize(ref Items, Items.Length + 1);
Items[Items.Length - 1] = Item;
}
else
Items = new T[] { Item };
}
不过,我认为使用List<T>
会是更好的选择。
我认为这应该有效。正如你自己建议的那样,只需使用泛型。为了在你的方法中实现这一点,你只需在任何地方更改一个变量类型,它的值在括号之间(它不一定是T,但这是惯例)
internal static void AssignNewArrayItem<T>(ref T[] Items, T Item)
{
if (Items != null)
{
Array.Resize(ref Items, Items.Length + 1);
Items[Items.Length - 1] = Item;
}
else
Items = new T { Item };
}
不过,您可能应该对该方法进行约束。你有你想要的基本类型吗?如果是这样,你可以这样做:
internal static void AssignNewArrayItem<T>(ref T[] Items, T Item)
where T : <base class name>
您可以使用通用约束,该约束将只接受从类Xml.CLASSNAME
继承的对象
internal static void AssignNewArrayItem<T>(ref T[] Items, T Item) where T: Xml.CLASSNAME
{
if (Items != null)
{
Array.Resize(ref Items, Items.Length + 1);
Items[Items.Length - 1] = Item;
}
else
Items = new Xml.CLASSNAME[] { Item };
}