score:1
Accepted answer
try something like this..
public enum diettype {carnivore, herbivore, omnivore};
public class factoryattribute : attribute
{
public object something { get; protected set; }
}
[attributeusage(system.attributetargets.class)]
public class diettypeattribute : factoryattribute
{
public diettypeattribute(diettype diettype)
{
this.something = diettype;
}
}
public abstract class diet { }
[diettypeattribute(diettype.carnivore)]
public class carnivore : diet
{
}
[diettypeattribute(diettype.herbivore)]
public class herbivore : diet
{
}
abstract class abstractfactory<t> where t : class
{
protected dictionary<enum, type> types;
protected abstractfactory()
{
}
protected void register<tenumtype, tsubtype>()
where tenumtype: factoryattribute
{
types = (from assembly in appdomain.currentdomain.getassemblies()
from type in assembly.gettypes()
let attributes = type.getcustomattributes(typeof(tenumtype), true)
where (attributes.any()) && (typeof(tsubtype).isassignablefrom(type)) && (type.isclass)
select
new
{
dietenum = (enum)((tenumtype)attributes.first()).something,
diettype = type
}).todictionary(x => x.dietenum, x => x.diettype);
}
public t createinstance(enum id, params object[] param)
{
return (t)activator.createinstance(types[id], param);
}
}
class dietfactory : abstractfactory<diet>
{
public dietfactory()
{
register<diettypeattribute, diet>();
}
}
and testing...
void main()
{
abstractfactory<diet> factory = new dietfactory();
diet diet = factory.createinstance(diettype.carnivore);
//diet is a 'carnivore'
diet = factory.createinstance(diettype.herbivore);
//diet is a 'herbivore'
}
edit: you don't actually need the template types for this
abstract class abstractfactory<t> where t : class
{
protected dictionary<enum, type> types;
protected abstractfactory()
{
types = (from assembly in appdomain.currentdomain.getassemblies()
from type in assembly.gettypes()
let attributes = type.getcustomattributes(typeof(factoryattribute), true)
where (attributes.any()) && (typeof(t).isassignablefrom(type)) && (type.isclass)
select
new
{
dietenum = (enum)((factoryattribute)attributes.first()).something,
diettype = type
}).todictionary(x => x.dietenum, x => x.diettype);
}
public t createinstance(enum id, params object[] param)
{
return (t)activator.createinstance(types[id], param);
}
}
and your factory is simply:
class dietfactory : abstractfactory<diet>
{
public dietfactory()
{
}
}
Source: stackoverflow.com
Related Query
- Self registered factory using reflection in c#
- How to refactor repeated code using reflection
- Convert string[] to int[] in one line of code using LINQ
- C# - code to order by a property using the property name as a string
- How do I find the text within a div in the source of a web page using C#
- Entity-framework code is slow when using Include() many times
- Entity Framework 4: Eager Loading (Include) with filters using Self Tracking Entities
- Left outer join using LINQ -- understanding the code
- How to reuse a linq expression for 'Where' when using multiple source tables
- Avoiding code repetition when using LINQ
- Using LINQ to delete an element from a ObservableCollection Source
- can my code improve from using LINQ?
- LINQ Source Code Available
- How to find all classes that implements a generic abstract class using reflection in C#?
- How to find out if an object's type implements IEnumerable<X> where X derives from Base using Reflection
- Creating an IEnumerable<> from a generator method using a factory function
- .NET 4 Code Contracts: "requires unproven: source != null"
- Get properties of class by order using reflection
- How can I write the following code more elegantly using LINQ query syntax?
- How can I code an outer join using LINQ and EF6?
- Explanation of Code : retrieve item from Array using FirstorDefault()
- C# .Net 3.5 Code to replace a file extension using LINQ
- Entity Framework Code First using context in Controller
- Trying to understand LINQ code using c#
- Retrieve bool result by using LinQ code
- Get Entity From Table Using Reflection From Abstract Type
- Unit testing code using IQueryable
- How can I combine IObservable<T>.Throttle() with some other event source using Reactive Extensions?
- creating Linq to sqlite dbml from DbLinq source code
- Simple Edit/Update actions using LINQ. Isn't my code a bit wrong?
More Query from same tag
- Why does the Contains() operator degrade Entity Framework' Linq queries?
- Linq and EF: Querying to get results on one to many relationships: Selecting table with foreign Key
- COUNT(DISTINCT *) in ef core 2.1
- Filter a list of string with wildcard
- Approach - Optimizing LINQ for performance
- Transform a List<object> of anonymous type to a Dictionary<string, SortedList<DateTime, double>>
- int? and int comparison when LEFT OUTER JOIN in Linq issue
- Set PredicateBuilder also on child collection
- CosmosDb Linq Count v3 SDK
- how to Update the value if already exists in database, if not then insert new record?
- MVC3 select int value through LINQ
- App_Data folder shadow folder empty
- MVC / EF Code First ICollection Objects
- C# Return a Calculated Distance between two Lat/Long Coordinates within a Linq Query WHERE statement
- C# Compare 2 List Object and create a third
- IEnumerator for HashTable?
- Elegant way to combine multiple collections of elements?
- How to cast returned value of XPathEvaluate?
- C# Linq To Create Group On Multiple Properties and format the resultant group into single key/property?
- LINQ GroupBy and then OrderBy a property from the previous query
- Create dynamic LINQ expression for Select with FirstOrDefault inside
- Linq splitting group if there is missing number
- Linq convert SQL response from one class to nested class output on group by .net core
- LINQ GroupBy - Select lowest ID group by name
- Entity Framework, how to use IQueryable with multiple where are translated to SQL?
- Filter List<Point> as per given Condition using LINQ
- Search DataRow with Linq and delete from Dataset
- Which sql query will be formed while using skip and take in entity framework?
- LINQ - Left outer join to attach list to parent object
- How to check if xElement value exists?