让用户输入字符串并使用该字符串创建对象
所以我一直在寻找这种感觉像永远的东西,不知道我做错了什么。下面是我的代码摘录,我想串CashierLOgInNName的值是新的出纳对象名称:让用户输入字符串并使用该字符串创建对象
public class Cashiers
{
public int CashierID;
public int Password;
public string FirstName;
public string LastName;
public void SetCashiers(int CashierID, int Password,string FirstName, string LastName)
{
this.CashierID = CashierID;
this.Password = Password;
this.FirstName=FirstName;
this.LastName = LastName;
}
Console.WriteLine("enter New Log in name");
string CashierLOgInNName= Console.ReadLine();
Console.WriteLine("enter First Name");
string CashierFirstName = Console.ReadLine();
Console.WriteLine("enter Last name");
string CashierLastName = Console.ReadLine();
Console.WriteLine("enter Cashier ID");
string f = Console.ReadLine();
int NewCashierID = Int32.Parse(f);
Console.WriteLine("enter Cashier Password");
string g = Console.ReadLine();
int NewCashierPWD = Int32.Parse(g);
CashierLOgInNName = (Cashiers)Activator.CreateInstance(null, CashierLOgInNName).Unwrap();
首先一点校正。它将确保收银员对象收银员对象已创建。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Activators
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter New Log in name");
string CashierLOgInNName = Console.ReadLine();
Console.WriteLine("enter First Name");
string CashierFirstName = Console.ReadLine();
Console.WriteLine("enter Last name");
string CashierLastName = Console.ReadLine();
Console.WriteLine("enter Cashier ID");
string f = Console.ReadLine();
int NewCashierID = Int32.Parse(f);
Console.WriteLine("enter Cashier Password");
string g = Console.ReadLine();
Cashiers cashierObj = (Cashiers)Activator.CreateInstance(typeof(Cashiers), f, g, CashierFirstName, CashierLastName);
}
}
public class Cashiers
{
public string CashierID;
public string Password;
public string FirstName;
public string LastName;
public Cashiers(string CashierID, string Password, string FirstName, string LastName)
{
this.CashierID = CashierID;
this.Password = Password;
this.FirstName = FirstName;
this.LastName = LastName;
}
}
}
来到下一部分CashierLOgInNName的值为新的收银对象名称。这似乎是棘手和无用的。我建议有更好的选择:
- 您可以在收银台中定义属性
loginName
。 - 您可以创建
Dictionary<string, Cashier>
LoginName作为键,并将Cashier Object作为值。
但仍,如果你坚持有使用CSharpCodeProvider类它允许动态创建从源代码的程序集的方式。 在源代码中,您可以将对象名称写入loginName,然后动态引用该程序集。
然而,它不为您提供任何用途,因为您将无法在运行时仅使用该对象,因为它的名称仅在运行时才为您所知。我希望它能帮助你的好奇心。
“在毁灭的时候,创造的东西。” - 为什么你使用`Activator`亭亭
这是一个巨大的帮助。但请原谅我对c#很陌生,使用Dictionary
Dictionary
activator.createinstance的MSDN文档和objecthandle.unwrap可能会有所帮助。
谢谢,但阅读,只是made.me更困惑。我需要更多的C#练习,然后我会回到那个,然后再试一次 – DANS80 2014-10-27 18:13:33
为什么你需要使用激活类?你打算使用.NET Remoting吗? – junPac 2014-10-27 23:58:06
这只是一个示例项目,以了解我在做什么。激活者类只是一个尝试。我不知道如何让用户输入一个字符串,然后使用该字符串作为新对象的名称。 I.E.如果我分配一个char newName =“SJones”;如何拿这个变量,并说出收银员的等价物SJones =新收银员(); – DANS80 2014-10-28 00:08:51
而不是简单地通过创造新的'收银员()'类? – abto 2014-10-27 07:53:39