Structs as Generic Arguments
I have several classes that implement something like an IAdd interface/class:
public class AddClass<T> where T : ISomething
{
//Calculated Properties
//Member Variables
public Add(T t)
{
//do stuff thats complicated
}
}
Now开发者_如何学运维 in some instances the t in Add(T t) just needs to be a simple struct with basically input variables; something like:
int ID;
string Name;
int Age;
From there I do some complicated stuff within the Add() method, but once I have 3 three inputs, I don't need anything else. I can probably just use a struct that implements ISomething. Is there a design pattern or anything that relates to this? Do I declare the struct within AddClass? What do I name it? Is there a standard approach for something like this?
t
in this case would be considered a Parameter Object.
As for how you get an instance of ISomething
, a DefaultSomething
(either class or struct is fine, you probably want a class unless you have a good reason) is pretty normal to have. If the DefaultSomething
is meant to only be used in the context of AddClass
you could nest it, otherwise I would declare it on its own.
There are no type restriction which can define a struct. However, if you use the following restriction you have limited quite a lot:
public class AddStruct<T> where T : struct, IConvertible, IFormattable, IComparable
I've blogged about it: http://blog.gauffin.org/2011/07/generic-type-restriction-for-enums/
精彩评论