Feedback

C# - Emulating F#''s ''with'' Construct in C# using Parameter Object

Veröffentlicht von am 13.12.2009
(2 Bewertungen)
This snippet introduces a way to emulate F#'s 'with' construct in C#. In particular, it shows how a factory method can be implemented which creates a new object based on a provided template object and optional additional values (replacing values of the template object) in a type-safe way. The following code shows an example using the proposed pattern:


var a1 = factory.CreateAttribute(
null,
new AttributeArgs {
StereoType = "author-info",
Name = "full-name",
Value = "Johann Duscher"
});

var a2 = factory.CreateAttribute(
a1,
new AttributeArgs {
Value = "Jonny Dee"}
});


While the presented solution doesn't use new C# 4.0 language features, using them for this task is also considered and discussed here: http://wp.me/pcfBw-6
GFU-Schulungen  [Anzeige]

VB.NET Aufbau

Sie verfügen nach der Schulung über fundierte Kenntnisse in der Arbeit mit objektorientierten Modellen in VB.NET und können wiederverwendbare Komponenten eigenständig erzeugen.

XML und .NET Überblick

Um auf dem neuesten Wissensstand zu sein, sollten Sie unser aktuelles ASP .NET Komplett Seminar belegen.
Nach dem Seminar kennen Sie die wichtigsten Strömungen in der Software-Technologie

public interface IAttribute
{
   string StereoType { get; set; }
   string Name { get; set; }
   string Value { get; set; }
}

public class AttributeArgs : IAttribute
{
   private string _stereoType;
   private string _name;
   private string _value;

   public string StereoType
   {
      get { return _stereoType; }
      set { _stereoType = value; StereoTypeSpecified = true; }
   }

   public bool StereoTypeSpecified { get; private set; }

   public string Name
   {
      get { return _name; }
      set { _name = value; NameSpecified = true; }
   }

   public bool NameSpecified { get; private set; }

   public string Value
   {
      get { return _value; }
      set { _value = value; ValueSpecified = true; }
   }

   public bool ValueSpecified { get; private set; }
}

public class Factory
{
   public IAttribute CreateAttribute(IAttribute template,
                                     AttributeArgs args)
   {
      if (null != template)
      {
         if (!args.StereoTypeSpecified)
            args.StereoType = template.StereoType;
         if (!args.NameSpecified)
            args.Name = template.Name;
         if (!args.ValueSpecified)
            args.Value = template.Value;
      }
      return new AttributeArgs {StereoType = args.StereoType,
                                Name = args.Name,
                                Value = args.Value,};
   }
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!