Skip to content

Instantly share code, notes, and snippets.

@vdonchev
Created December 17, 2015 08:56
Show Gist options
  • Save vdonchev/b55abe9a97f89b8c1dd5 to your computer and use it in GitHub Desktop.
Save vdonchev/b55abe9a97f89b8c1dd5 to your computer and use it in GitHub Desktop.
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