[英]How to define a namespace based template class or function in c#?
In C#, could I define a class like this, T
is a namespace name here, in stead of a data type name. 在C#中,我可以定义这样的类吗, T
是这里的名称空间名称,而不是数据类型名称。
public class MyClass<T>
{
T.DataType_Defined_in_T t;
...........
}
or in a function: 或功能中:
public void MyFunction<T>(T.DataType_Defined_in_T t)
{
...............
}
Is there a way to achieve this goal? 有没有办法实现这个目标?
Or, something can switch the reference using in run-time: 或者,可以在运行时使用来切换引用:
between: 之间:
using namespace np1;
and 和
using namespace np2;
There is no way to do this using namespaces, but you could implement a class that acts as an accessor or factory for the types in the namespace. 无法使用名称空间来执行此操作,但是您可以实现一个类,该类充当名称空间中类型的访问器或工厂。
interface IFactory
{
Type GetType1();
}
namespace X
{
public class Type1 { }
public class Factory : IFactory
{
public Type GetType1() { return typeof(Type1); }
}
}
namespace Y
{
public class Type1 { }
public class Factory : IFactory
{
public Type GetType1() { return typeof(Type1); }
}
}
public void MyFunction<T>(T factory)
where T : IFactory
{
var type = factory.GetType1();
...
}
void Main()
{
MyFunction(new X.Factory());
MyFunction(new Y.Factory());
}
Or you would implement a non-generic reflection solution: 或者,您可以实施非通用反射解决方案:
public void MyFunction(string ns)
{
var typesReader = from asm in AppDomain.CurrentDomain.GetAssemblies()
from type in asm.GetExportedTypes()
where type.Namespace == ns
select type;
var typeMap = typesReader.ToDictionary(t => t.Name);
var type1 = typeMap["Type1"];
...
}
void Main()
{
MyFunction("X");
MyFunction("Y");
}
Note that this reflection solution won't work if the assembly(-ies) containing the namespace(s) aren't loaded in the appdomain yet. 请注意,如果尚未在appdomain中加载包含名称空间的程序集,则此反射解决方案将无法使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.