Created
December 17, 2015 08:56
-
-
Save vdonchev/b55abe9a97f89b8c1dd5 to your computer and use it in GitHub Desktop.
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
namespace Sandbox2 | |
{ | |
using System; | |
using System.Linq; | |
using System.Reflection; | |
public static class Program | |
{ | |
public static void Main() | |
{ | |
var personGenerator = new PersonGenerator(); | |
IPerson student = personGenerator.Generate("Student"); | |
Console.WriteLine(student.Name); | |
} | |
} | |
public class PersonGenerator | |
{ | |
public IPerson Generate(string typeName) | |
{ | |
var personType = Assembly | |
.GetEntryAssembly() | |
.GetTypes() | |
.FirstOrDefault( | |
type => | |
type.CustomAttributes.Any(a => a.AttributeType == typeof (PersonAttribute)) && | |
type.Name == typeName); | |
if (personType == null) | |
{ | |
throw new ArgumentNullException(); | |
} | |
var person = Activator.CreateInstance(personType) as IPerson; | |
return person; | |
} | |
} | |
[Person] | |
public class Student : IPerson | |
{ | |
public Student(string name = "Name") | |
{ | |
this.Name = name; | |
} | |
public string Name { get; private set; } | |
} | |
public interface IPerson | |
{ | |
string Name { get; } | |
} | |
[AttributeUsage(AttributeTargets.Class)] | |
public class PersonAttribute : Attribute | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment