我正在使用C#开发一个具有在表单上声明的接口的应用程序:
public partial class frmProjectForm : Form, IProjectInfo
{
}
public interface IProjectInfo
{
string ProjectName { get; set; }
string ProjectTitle { get; set; }
string ProjectDescription { get; set; }
string ProjectAuthor { get; set; }
string ProjectCopyright { get; set; }
string ProjectTrademark { get; set; }
string ProjectCreationDate { get; set; }
string ProjectVersion { get; set; }
string ProjectFileName { get; }
string ProjectFilePath { get; }
string FullProjectPath { get; }
}
在应用程序的某个地方我想这样做:
frmProjectForm f = new frmProjectForm();
f.ShowDialog(this);
...
...
IProjectInfo getProjectInfoMembersOnly = (IProjectInfo)f;
// persist the IProjectInfo members to JSON
string project = JsonConvert.SerializeObject( getProjectInfoMembersOnly );
JsonConvert.SerializeObject方法正在爆炸并抱怨Button控件上的一些自引用循环.转换操作不排除表单,我不知道为什么因为我只希望接口转换只返回接口成员.
我究竟做错了什么?
最佳答案 对我来说,序列化代码可以处理对象的实际类型,而不是作为参数传递的类型(这甚至可能是函数接受对象类型的参数,而不是通用函数SerializeObject< T>(T obj)似乎是正常的. )).
如果你想要切割你的对象,我恐怕你必须自己执行切片,创建一个实现接口的对象并只复制其成员.
public class ProjectInfo : IProjectInfo
{
public string ProjectName { get; set; }
public string ProjectTitle { get; set; }
public string ProjectDescription { get; set; }
public string ProjectAuthor { get; set; }
public string ProjectCopyright { get; set; }
public string ProjectTrademark { get; set; }
public string ProjectCreationDate { get; set; }
public string ProjectVersion { get; set; }
public string ProjectFileName { get; private set; }
public string ProjectFilePath { get; private set; }
public string FullProjectPath { get; private set; }
public ProjectInfo(IProjectInfo src)
{
this.ProjectName = src.ProjectName;
this.ProjectTitle = src.ProjectTitle;
this.ProjectDescription = src.ProjectDescription;
this.ProjectAuthor = src.ProjectAuthor;
this.ProjectCopyright = src.ProjectCopyright;
this.ProjectTrademark = src.ProjectTrademark;
this.ProjectCreationDate = src.ProjectCreationDate;
this.ProjectVersion = src.ProjectVersion;
this.ProjectFileName = src.ProjectFileName;
this.ProjectFilePath = src.ProjectFilePath;
this.FullProjectPath = src.FullProjectPath;
}
}
然后你可以这样使用它:
frmProjectForm f = new frmProjectForm();
f.ShowDialog(this);
...
...
IProjectInfo getProjectInfoMembersOnly = new ProjectInfo(f); //I only changed this line
// persist the IProjectInfo members to JSON
string project = JsonConvert.SerializeObject( getProjectInfoMembersOnly );