Created
June 26, 2010 23:03
-
-
Save anonymous/454424 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
using System; | |
using System.Linq; | |
using System.Runtime.InteropServices; | |
namespace Reflection | |
{ | |
public static class ExtendedActivator | |
{ | |
public static object CreateInstance(Type type) | |
{ | |
var constructors = type.GetConstructors(); | |
var defaultConstructor = constructors.SingleOrDefault(c => !c.GetParameters().Any()); | |
if (defaultConstructor == null) | |
{ | |
var pseudoDefaultConstructor = constructors.FirstOrDefault( | |
ci => ci.GetParameters().All( | |
p => p.GetCustomAttributes(typeof(OptionalAttribute), false).Any())); | |
if (pseudoDefaultConstructor == null) | |
throw new InvalidOperationException("No default constructor found"); | |
return pseudoDefaultConstructor.Invoke(pseudoDefaultConstructor.GetParameters() | |
.Select(p => p.DefaultValue).ToArray()); | |
} | |
return Activator.CreateInstance(type); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment