[英]How to pass object as parameter in c#
抱歉,我可能缺少术语,但是尽管有一些琐碎的问题,但我的搜索没有提供任何答案。 开始 -
我有一个超类,并希望能够使用如下方法创建任何子类的新对象:
static void AddNewVehicle(string brand, string model, int year, int price)
{
V.Add(new Car(brand, model, year, price));
}
我以为我可以做到这一点:
static void AddNewVehicle(object VehicleType, string brand, string model, int year, int price)
{
V.Add(new VehicleType(brand, model, year, price));
}
...但是出现以下错误:
"The type or namespace name 'VehicleType' could not be found (are you missing a using directive or an assembly reference?)"
在您的方案中,已将VehicleType
指定为用类型object
声明的变量的名称。 您不能像这样实例化对象。
如果您可以提供有关问题的更多信息,我将尝试提供更具体的答案。
例如,您可以在Vehicle
类中添加一个名为VehicleType
的新属性,该属性应为enum
类型。
或者,如果您需要在一个集合中使用多种类型的车辆,则可能想实现factory pattern
并使用interfaces
来处理一个集合。
根据评论进行编辑:
有多种方法可以做到这一点,所以我提到了到目前为止其他人都没有提到的一种方法。 它基于reflection
。 基本上,您在程序集中搜索继承“超类”的类,如果它们的名称与提供的参数相对应,则将其实例化。
但是,我们可以通过使用称为Activator
的类来简化此过程。 我们需要的只是包含所需类的程序集的名称及其名称。 Activator将为我们创建其实例。
这是一个入门的示例:
public static SuperClass GetClass(string type)
{
return (SuperClass)Activator.CreateInstance("someAssemblyName", "type");
}
或来自MSDN的更多信息: http : //msdn.microsoft.com/zh-cn/library/b4wc81dc.aspx
当然,您可以在执行任何其他操作之前修改属性,例如:
public static SuperClass GetClass(string type, string brand, string model)
{
SuperClass sc = (SuperClass)Activator.CreateInstance("someAssemblyName", "type");
sc.Brand = brand;
sc.Model = model;
return sc;
}
如果要采用“ Factory
方法,则将其用作工厂。 一个静态类,为该类构造东西。 不多不少。 不要在该工厂中放置用于存储对象的状态(列表V
)。
然后是值得商bat的静态方法
static void AddNewVehicle(object VehicleType, string brand, string model, int year, int price)
{
V.Add(new VehicleType(brand, model, year, price));
}
您想在这里做什么? 您传递了一个名为VehicleType的对象,但您想在主体中构造一个新对象?
然后编译错误:
找不到类型或名称空间名称“ VehicleType”(您是否缺少using指令或程序集引用?)
这意味着您要么:
VehicleType
的类 VehicleType
类的名称空间的using
语句 VehicleType
的项目的引用。 (或以上任意组合)
您提供的代码示例中的其他一些单词
假设您具有以下类:
public class VehicleType
{
... some properties, constructors and methods
}
public class Car : VehicleType
{
... some properties, constructors and methods
}
然后,您将能够创建一个生产新车的工厂类,例如
public static class VehicleFactory
{
public static Vehicle CreateVehicle(...)
{
// conditional stuff that decides what kind of vehicle to construct
if (...)
{
return new Bicycle(...);
}
else if (...)
{
return new Car(...);
}
else
{
throw new UnsupportedVehicleException();
}
}
}
希望这对您有所帮助。
在C#中,类型信息通常以两种方式之一传递:类的实例Type ,或作为泛型类型参数。 后者为您提供静态类型检查和约束 。
其他答案中还提到了其他策略,但您可能会发现它们繁琐且不合适。
尝试这个:
class Vehicle
{
static ICollection<Vehicle> V;
string Brand;
string Model;
int Year;
int Price;
static void AddNewVehicle<T>(string brand, string model, int year, int price)
where T : Vehicle, new()
{
V.Add(new T() {
Brand = brand,
Model = model,
Year = year,
Price = price
});
}
}
请注意:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.