C# – 将字符串转换为类对象

我正在使用其他人的代码并尝试进行一些修改。 所以我需要做的是采取以下措施:

RemoteFileDP remoteFile = new DPFactory().CreateRemoteFileDP(configData); 

并更改它,以便remoteFile可以等于字符串变量中的内容。 为了进一步解释,让我再给出一些代码:

 ConfigDP configData = new ConfigDP(); 

所以上面的语句是在remoteFile语句之前执行的,而ConfigDP在它上面有两个类(抽象Config,然后是它的base:abstract ConfigBase)。 DP也是它上面两个抽象类的子代(抽象RemoteFile和抽象RemoteFileBase)。

根据我的理解,remoteFile是从数据库查询中提取的数据的结果,存储在列表或Hashtable中(抱歉只是一个实习生所以我正在研究这个)。

我需要remoteFile接受字符串值的原因是因为有很多方法利用了remoteFile中的信息,我想避免创建一个接受字符串值而不是RemoteFileDP remoteFile的重载方法的WHOLE BUNCH。

所以如果我可以取一个字符串值,如:

 string locationDirectory; 

从另一个方法传入,然后有类似于以下内容:

 RemoteFileDP remoteFile = locationDirectory; 

那么使用remoteFile的所有其他方法都不必重载或更改。

很抱歉所有细节,但这是我第一次发布,所以我希望我提供了足够的信息。 我确实看了C#将动态字符串转换为现有的Class和C#:使用运行时确定的类型实例化对象并编写以下代码:

 RemoteFilesDP remoteFile = (RemoteFileDP)Activator.CreateInstance(typeof(RemoteFileDP), locationDirectory); 

但是我一直得到一个“MissingMethodException”错误,找不到RemoteFileDP的构造函数,但我确实有如下所示的构造函数:

 public RemoteFileDP() { } //end of RemoteFilePlattsDP constructor 

提前感谢您的帮助!

您缺少一个将string作为参数的构造函数。 试试你的代码吧

 public RemoteFileDP(string locationDirectory) { // do stuff with locationDirectory to initialize RemoteFileDP appropriately } 

当然,如果你这样做,为什么不直接调用构造函数呢?

 RemoteFileDP remoteFile = new RemoteFileDP(locationDirectory); 

如果您不希望修改RemoteFileDP所在的源项目(或不能),您可以编写一个扩展方法,如下所示:

 public static RemoteFileDP ConvertToRemoteFileDP(this string location) { // Somehow create a RemoteFileDP object with your // location string and return it } 

这样你就可以运行你想要的代码行:

 RemoteFileDP remoteFile = locationDirectory; 

稍作修改如下:

 RemoteFileDP remoteFile = locationDirectory.ConvertToRemoteFileDP(); 

这会让你解决问题吗?

虽然我喜欢构造函数接受更多string的想法,但您可以在RemoteFileDPstring之间定义隐式或显式转换运算符:

  class RemoteFileDP { .... public static implicit operator RemoteFileDP(string locationDictionary) { //return a new and appropiately initialized RemoteFileDP object. //you could mix this solution with Anna's the following way: return new RemoteFileDP(locationDictionary); } } 

这样你实际上可以写:

  RemoteFileDP remoteFile = locationDirectory; 

或者,如果转换运算符是明确的:

  RemoteFileDP remoteFile = (RemoteFileDP)locationDirectory; 

我仍然坚持认为,Anna Lear的解决方案更好,因为隐式或显式转换似乎并不是最适合这种情况。 例如,如果由于locationDictionary值无效而导致转换失败,那么我不建议使用此路径。 如果转换始终是成功的,无论locationDictionary是什么值(禁止null ),那么它可能是您问题的有效解决方案。

我只是把它放在桌面上,因为我认为你可能会发现在C#中了解explicitimplicit转换是有用的,如果你还没有。