|
Partner
|
|
|
Emulating F#''s ''with'' Construct in C# using Parameter Object
Autor:
Johann Duscher
|
Sprache:
C#
|
Bewertung:
noch nicht bewertet
|
Anzahl der Aufrufe:
1748
|
Beschreibung:
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
Abgelegt unter: design pattern, f#, functional, mono, factory, parameter object, prototype.
|
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
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 Schreiben von Kommentaren bitte anmelden.)
|
|
Diese Snippets könnten für Sie interessant sein:
|
|
|
|
|
|
|
|
|