将对象状态序列化为 const C# 类

发布于 2025-01-03 10:55:11 字数 1026 浏览 2 评论 0原文

有几次,我发现自己想要获取一个对象的状态,并将其变成一个常量。 例如。我正在设计一个用户界面,它显示来自数据库调用的信息。 我只是想要一个可以使用的数据样本,这样我就可以看到一切都会是什么样子。

假设我有:

public interface IPerson
{
   string Name{get;}
   string Age {get;}
   ...
}

public class Person
{
   string Name{get; set}
   string Age {get; set}
   ...

}

以及一些确实表示数据库调用或加载它的方法。 对于这个例子,为了简单起见,我们从 CSV 文件加载它: 对于这个例子,文件包含:“Mrs McKenzy,56,..”

IPerson Load(string fileName)
{
    var text = File.ReadAllText(filename);
    var parts = text.Split(",");
    return new Person()
    {
        Name = parts[0],
        Age = Int32.Parse(parts[1]),
        ...
    }
}

由此我想生成我的示例类:(作为.cs文件)

public class SamplePerson : IPerson
{
    string Name{get {return "Mrs McKenzy"}}
    string Age {get {return 56}}
    ...  
}

我能看到的唯一方法是序列化对象(可能是XML ,这样我就可以看到其中的内容),然后让我的 SamplePerson 在其构造函数中反序列化该对象,以初始化自身。 现在这不是一个糟糕的解决方案。 但我认为如果我可以“序列化为 C#”会更好。 似乎可以将一些东西放在一起,而无需反思太多麻烦, 所以我想知道是否有一些现有的库。 (如果不是的话,我想如果我有机会的话这可能是一个有趣的项目)

A couple of times, i've found myself wanting to take the state of an object, and make it into a constant.
Eg. I'm designing a UI, that displays informatation from say a database call.
and I just want a sample of the data to play around with, so i can see what everything would look like.

Let say I have:

public interface IPerson
{
   string Name{get;}
   string Age {get;}
   ...
}

public class Person
{
   string Name{get; set}
   string Age {get; set}
   ...

}

and some method that does say the database call, or what ever to load it.
For this example lets say for simpicities sake it loads it from a CSV file:
for this example the file contains: "Mrs McKenzy, 56,.."

IPerson Load(string fileName)
{
    var text = File.ReadAllText(filename);
    var parts = text.Split(",");
    return new Person()
    {
        Name = parts[0],
        Age = Int32.Parse(parts[1]),
        ...
    }
}

from this I want to generate my sample class: (as a .cs file)

public class SamplePerson : IPerson
{
    string Name{get {return "Mrs McKenzy"}}
    string Age {get {return 56}}
    ...  
}

The only way I can see of doing this is serialise the object (prob to XML, so i can see what is in it), and then have my SamplePerson deserialise the object in its constructor, to intitialise itself.
Now this isn't a bad solution.
But I figure it would be nicer if I could just "Serialise to C#".
Seems like something that could be put together without too much trouble with reflection,
so I'm wondering if there is some existing library for it.
(If not I guess it could be a fun project if ever I get bord)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

睡美人的小仙女 2025-01-10 10:55:11

也许您可以将机制抽象为接口,例如:

public interface IPersonRepository
{
  IPerson GetPerson(int id);
}

并提供设计时实现。

public class DesignTimePersonRepository : IPersonRepository
{
  public IPerson GetPerson(int id)
  {
    return new DesignTimePerson { Name = "Joe Bloggs", Age = 56 };
  }
}

现在,假设您可以确定是否处于设计模式,您可以执行以下操作:

public IPersonRepository GetPersonRepository()
{
  return DesignMode
    ? new DesignTimePersonRepository()
    : _container.Resolve<IPersonRepository>();
}

Perhaps you can abstract the mechanism to an interface, something like:

public interface IPersonRepository
{
  IPerson GetPerson(int id);
}

And provide a design-time implementation.

public class DesignTimePersonRepository : IPersonRepository
{
  public IPerson GetPerson(int id)
  {
    return new DesignTimePerson { Name = "Joe Bloggs", Age = 56 };
  }
}

Now, assuming you can determine whether you're in Design mode, or not, you could do something like:

public IPersonRepository GetPersonRepository()
{
  return DesignMode
    ? new DesignTimePersonRepository()
    : _container.Resolve<IPersonRepository>();
}
冷默言语 2025-01-10 10:55:11

据我了解,您希望将对象属性保存为硬编码值。
为什么要这样做呢?

根据您的标记,我可以猜测您希望能够获取但不设置该值。
如果是这种情况,您可以使用以下方法。

// make a public interface
public interface IPerson {
    String Name { get; }
    String Age { get; }
}

public class Manager {
    public IEnumerable<IPerson> GetPeople() {
        var retVal = new List<Person>();
        // Do your retrieval. Here you can access
        // the setters of your class. 
        return retVal;
    }
    // make a private implementation
    private class Person : IPerson {
        public String Name { get; set; }
        public String Age { get; set; }

        // explicit interface implementation
        String IPerson.Name {
            get { return Name; }
        }

        String IPerson.Age {
            get { return Age; }
        }
    }
}

这种方法允许您隐藏实际的实现并限制对属性的访问,使其只读。

As I understand you want to save the object properties as a hard coded value.
Why to do so?

According to your markup I can guess you wish to be able to get but not set the value.
If this is a case you might use the following approach.

// make a public interface
public interface IPerson {
    String Name { get; }
    String Age { get; }
}

public class Manager {
    public IEnumerable<IPerson> GetPeople() {
        var retVal = new List<Person>();
        // Do your retrieval. Here you can access
        // the setters of your class. 
        return retVal;
    }
    // make a private implementation
    private class Person : IPerson {
        public String Name { get; set; }
        public String Age { get; set; }

        // explicit interface implementation
        String IPerson.Name {
            get { return Name; }
        }

        String IPerson.Age {
            get { return Age; }
        }
    }
}

This approach allows you to hide the actual implementation and restrict the access to the properties making them only readable.

鹤仙姿 2025-01-10 10:55:11

怎么样,使用 CSharpCodeProvider,编译你的类,然后实例化它并使用动态.....

void Main()
{
    dynamic instanceOfMyType;

    using (CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider())
    {

        var outPutFile = Path.ChangeExtension(Path.GetTempFileName(), ".dll");
        CompilerParameters parameters = new CompilerParameters()
        {
            //For creating DLLs it should be false
            GenerateExecutable = false,
            OutputAssembly = outPutFile,
            //For displaying warnings in the compilerResults
            WarningLevel = 4,

        };
        //I am reading the text from a WPF RichTextbox
        var text = File.ReadAllText(@"c:\temp\SampleFoo.cs");
        CompilerResults compilerResults = csharpCodeProvider.CompileAssemblyFromSource(parameters, text);

        var type = compilerResults.CompiledAssembly.GetType("SampleFoo");
        instanceOfMyType = Activator.CreateInstance(type);
    }
    Console.WriteLine (instanceOfMyType.Bar);
}

*如何在运行时编译 C# 代码片段


或者您可以在 SamplePerson 类中将 IPerson 作为 dll 共享

...... ......

How about this, using the CSharpCodeProvider, compile your class, then instance it and use dynamics.....

void Main()
{
    dynamic instanceOfMyType;

    using (CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider())
    {

        var outPutFile = Path.ChangeExtension(Path.GetTempFileName(), ".dll");
        CompilerParameters parameters = new CompilerParameters()
        {
            //For creating DLLs it should be false
            GenerateExecutable = false,
            OutputAssembly = outPutFile,
            //For displaying warnings in the compilerResults
            WarningLevel = 4,

        };
        //I am reading the text from a WPF RichTextbox
        var text = File.ReadAllText(@"c:\temp\SampleFoo.cs");
        CompilerResults compilerResults = csharpCodeProvider.CompileAssemblyFromSource(parameters, text);

        var type = compilerResults.CompiledAssembly.GetType("SampleFoo");
        instanceOfMyType = Activator.CreateInstance(type);
    }
    Console.WriteLine (instanceOfMyType.Bar);
}

*How to compile C# code snippet in runtime


or you can share the IPerson as a dll en the SamplePerson class.....

........

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文