Skip to main content
 首页 » 编程设计

c#之如何更改此代码以返回多个不同的项目

2024年02月13日17zhenyulu

这个工厂的例子; http://www.dotnetperls.com/factory 返回 1 个东西。我将如何更改它以返回这样的内容;

string device = ""; 
string deviceTypeID = ""; 
int deviceTypeCode = 0; 
bool true 

举个例子,在每个具体类中,我会让它看起来像这样;

string device = "bracelet"; 
string deviceTypeID = "male"; 
int deviceTypeCode = 0; 
bool true 

或者,对于另一个具体类;

string device = "ring"; 
string deviceTypeID = "female"; 
int deviceTypeCode = 8; 
bool false 

我想我需要在每个具体类中创建一个对象,但由于我是 C# 的新手,所以这扩展了我的理解。

谢谢!

请您参考如下方法:

将它们分组到一个类

sealed class MyClass  
{ 
    public MyClass(string device, string deviceTypeId, int deviceTypeCode, bool someBool) 
    { 
        this.Device = device; 
        this.DeviceTypeId = deviceTypeId; 
        this.DeviceTypeCode = deviceTypeCode; 
        this.SomeBool = someBool 
    } 
 
    string Device { get; private set; } 
    string DeviceTypeId { get; private set; } 
    int DeviceTypeCode { get; private set; } 
    bool SomeBool { get; private set; } 
} 

然后返回到你的工厂。

return new MyClass("bracelet", "male", 0, false); 

你的类的实现可能会有所不同,我在这里实现了它,所以你只能从中读取它(创建后不能更改它)。