简体   繁体   English

如何在 C# 中创建与特定变量具有相同数据类型的新变量?

[英]how can I create a new variable with the same data type of a specific variable in C#?

I want to create a new variable in the same data type of my variable Message .我想在与我的变量Message相同的数据类型中创建一个新变量。 How can I do that?我怎样才能做到这一点?

I tried the following code.我尝试了以下代码。 but I got an error.但我有一个错误。

MessageDTO Message;
var Message2 = new Message.GetType();

Error:错误:

Message is a variable but is used like a type. Message 是一个变量,但用作类型。

Here is my code:这是我的代码:

public string Send(MessageDTO message)
{
     MessageDTO Message2 = new MessageDTO();
     if (message is Email)
     {
         Message2= new Email();
     }else if(message is SMS)
     {
         Message2= new SMS();
     }
    // rest of code ...
 }

Where在哪里

 public class MessageDTO
 {
        public int Id { get; set; }
        public MessageType Type { get; set; }
        public string? Subject { get; set; }
        public string? TextBody { get; set; }
        public string? HTMLBody { get; set; }
        public DateTimeOffset SendDate { get; set; }
        public DateTime SendTime { get; set; }
 }

public class Email : MessageDTO
{
   public string From{ get; set; }
   public string To{ get; set; }
}



 public class SMS : MessageDTO
 {
   public string SenderLine{ get; set; }
   public string[] To{ get; set; }
 }

I want to make my code open for extension, but closed for modification (ie If I add other types of messages, the Send method remains unchanged.).我想让我的代码对扩展开放,但对修改关闭(即如果我添加其他类型的消息, Send方法保持不变。)。 The Send method becomes shorter like this: Send方法变得更短,如下所示:

public string Send(MessageDTO message)
{
     MessageDTO Message2 = new Activator.CreateInstance(Message.GetType());
     // rest of code ...
 }

Its not clear to me why you need to make a new object in Send() .我不清楚为什么需要在Send()中创建一个新的 object 。 Knowing that, maybe another solution would be better.知道这一点,也许另一种解决方案会更好。 But I'll just go with the assumption that it is necessary.但我只是假设它是必要的 go 。

One approach is to have MessageDTO be responsible for creating a new object of the correct type:一种方法是让MessageDTO负责创建正确类型的新 object:

public class MessageDTO
{
    public abstract MessageDTO CreateAnother();
}

public class Email : MessageDTO
{
   public override MessageDTO CreateAnother() => new Email();
}

...

public string Send(MessageDTO message)
{
   MessageDTO Message2 = message.CreateAnother();
}

The CreateAnother() function could also do something more sophisticated, depending on what you need. CreateAnother() function 还可以根据您的需要做一些更复杂的事情。 For instance it could clone the existing object, not just create a default new one.例如,它可以克隆现有的 object,而不仅仅是创建默认的新 object。 (In that case I'd probably name it differently!) (在那种情况下,我可能会以不同的方式命名它!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM