Created
September 15, 2015 14:06
-
-
Save bonprosoft/62dfcbc157d95b7c7d96 to your computer and use it in GitHub Desktop.
Genericsの制約
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var foo = SingletonClass<List<string>>.GetInstance(); | |
foo.Add("bbb"); | |
foo.Add("aaa"); | |
var anotherFoo = SingletonClass<List<string>>.GetInstance(); | |
Console.WriteLine(String.Join(",", anotherFoo)); | |
var bar = SingletonClass<List<int>>.GetInstance(); | |
Console.WriteLine(bar.Count); | |
var baz = SingletonClass<FooClass>.GetInstance(); // Error | |
} | |
} | |
public class FooClass | |
{ | |
public string Foo { get; set; } | |
public FooClass(string foo) | |
{ | |
this.Foo = foo; | |
} | |
} | |
public class SingletonClass<T> | |
where T : new() | |
{ | |
private static T instance = default(T); | |
public static T GetInstance() | |
{ | |
if (instance == null) | |
{ | |
instance = new T(); | |
} | |
return instance; | |
} | |
private SingletonClass() | |
{ | |
// Initialize here. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment