Skip to content

Instantly share code, notes, and snippets.

@bonprosoft
Created September 15, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bonprosoft/62dfcbc157d95b7c7d96 to your computer and use it in GitHub Desktop.
Save bonprosoft/62dfcbc157d95b7c7d96 to your computer and use it in GitHub Desktop.
Genericsの制約
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