如何将结构实例分配给包含该结构的类?

时间:2014-09-05 09:21:13

标签: c# .net struct

我之前从未使用过结构。我已经创建了一个简单的例子,说明了我在下面尝试做的事情。我选择struts的原因是因为对象永远不需要存在于类的上下文之外。感谢。

public class EmailAddress
{
    public string Email { get; set; }

    public string Name { get; set; }
}


public class EmailMessage
{
    public EmailAddress To { get; set; }

    public EmailAddress From { get; set; }

    public string Subject { get; set; }

    public string Body { get; set; }

    public struct Attachment
    {
        public string Name { get; set; }

        public string Bas64 { get; set; }
    }

尝试方法

protected void MyMethod()
{
    var myEmailMessage = new EmailMessage
    {
        To = { Email = "ToEmailAddress" }, 
        From = { Email = "FromEmailAddress" }
    };

    var myAttachment = new EmailMessage.Attachment
    {
        Name = "AttachmentName", 
        Bas64 = "Base64String"
    };

    myEmailMessage.Attachment = myAttachment;
}

3 个答案:

答案 0 :(得分:4)

您不能使用struct声明作为您班级的财产。您应该拆分属性和实际的struct定义。

试试这个:

public _Attachment Attachment {get;set;} /* Attachment as property */

public struct _Attachment /* The definition of the struct */
{
    public string Name { get; set; }

    public string Bas64 { get; set; }
}

并像这样使用它:

var myAttachment = new EmailMessage._Attachment
{
    ...
}

顺便说一句:实际上并不需要struct。使用class也没关系。

答案 1 :(得分:1)

您的问题是myEmailMessage.Attachment = my Attachment;正在尝试将某些内容分配给名为Attachment的成员。问题是您的班级上没有名为Attachment的属性。你声明了一个struct,但这只是一个声明而且没有创建属性或类似的任何东西。

您需要的是在您的课程中拥有一个实际属性,然后您可以将Attachment的实例分配给。{/ p>

答案 2 :(得分:1)

您的EmailMessage课程没有Attachment属性,只有Attachment嵌套类型。

您应该将Attachment结构重命名为EmailAttachment以避免名称冲突,并创建Attachment属性:

public class EmailMessage
{
    public EmailAddress To { get; set; }

    public EmailAddress From { get; set; }

    public string Subject { get; set; }

    public string Body { get; set; }

    public EmailAttachment Attachment { get; set; }

    public struct EmailAttachment
    {
        public string Name { get; set; }

        public string Bas64 { get; set; }
    }
}
相关问题