【发布时间】:2016-09-01 13:49:06
【问题描述】:
我有一个场景(简化)如下:
public static class Example
{
public const int CONSTANT_VALUE = 1;
public static Example<T> Create<T>(IEnumerable<T> argument)
where T : class
{
return new Example<T>(argument);
}
//More overloads of Create<T>, possibly other static methods, etc..
}
public class Example<T>
where T : class
{
public Example(IEnumerable<T> argument)
{
//Do Stuff
//Nothing like this in the real code, just example
//that constants are used from the other class.
if (something == Example.CONSTANT_VALUE)
{
//Do A Thing
}
}
//Lots more code
}
基本思想是我可以通过静态类通过类名获得静态方法、常量等,而实际实现在类型参数的非静态类中。
我的问题是这是否是一个很好的设置方法。有没有办法在Example<T> 上放置一些不关心类型参数的静态方法和常量?还有其他更推荐的模式吗?我的工作正常,但我想知道是否还有其他方法,因为这是我第一次最终做这样的事情(并不是说它在概念上对我来说是新的,只是从来没有需要)。
【问题讨论】:
-
那么,您的类型参数是否适用于整个类(即所有方法),还是仅适用于一种方法有意义?
-
它适用于整个类,因为该类的主要目的(在我的例子中)是封装一个集合并提供使用它及其内容的方法(主要是返回 T 以供实际使用参数)。在实际代码中,我的类派生自 CollectionView 并实现 ICollectionView,静态类将传入的数据转换为对类型参数类的输入友好的格式,其中有一个常量,并且可能会使用更多静态变量/方法进行扩展根据需要。
-
Tuple也是如此:Tuple.Create(123, 456)返回一个Tuple<int, int>。 :) -
@Caramiriel - 是的,我认为微软有同样模式的例子,我想这至少在某些情况下证实了它是一个有效的模式。供其他人参考,这里是 Tuple 的参考来源,确实是相同的模式:referencesource.microsoft.com/#mscorlib/system/tuple.cs
标签: c# design-patterns static constants generic-type-argument