简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM