C#使用CodeDom将变量添加为类的一部分

C#使用CodeDom将变量添加为类的一部分,c#,codedom,C#,Codedom,我试图通过使用CodeDom创建以下代码: public partial class mainClass { public byte[] bytes = null; } 创建这个类没有问题,我找到了使用CodeVariableDeclarationStatement方法通过使用CodeDom声明变量的方法,但是我不确定如何将变量声明添加到我的类中 以下是我到目前为止所做的尝试: CodeTypeDeclaration mainClass = new CodeTypeDeclaratio

我试图通过使用CodeDom创建以下代码:

public partial class mainClass
{
    public byte[] bytes = null;
}
创建这个类没有问题,我找到了使用
CodeVariableDeclarationStatement
方法通过使用CodeDom声明变量的方法,但是我不确定如何将变量声明添加到我的类中

以下是我到目前为止所做的尝试:

CodeTypeDeclaration mainClass = new CodeTypeDeclaration("mainClass");
mainClass.IsPartial = true;
mainClass.IsClass = true;
mainClass.Attributes = MemberAttributes.Public;
Namespaces.Types.Add(mainClass);

CodeVariableDeclarationStatement variableDeclaration = new(CodeVariableDeclarationStatement(typeof(byte[]), "bytes", new CodePrimitiveExpression("String.Empty");
我愿意接受任何建议和想法。谢谢你的帮助, 埃文。

试着用这个

CodeMemberField field = new CodeMemberField(typeof(byte[]), "bytes");
field.Attributes = MemberAttributes.Public;

mainClass.Members.Add(field);

非常感谢。但是,如果我的声明是一个方法的一部分呢。我会使用我的原始代码吗?