相关疑难解决方法(0)

是否无法动态使用泛型?

我需要在运行时创建一个使用泛型的类的实例,比如class<T>,在不知道它们将具有的类型T的情况下,我想做类似的事情:

public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        lists.Add(type, new List<type>()); /* this new List<type>() doesn't work */
    }

    return lists;
}
Run Code Online (Sandbox Code Playgroud)

......但我做不到.我认为不可能在通用括号内的C#中写入一个类型变量.还有另一种方法吗?

c# generics

10
推荐指数
1
解决办法
1957
查看次数

如何将"Type"类型的变量传递给泛型参数

我正在尝试这样做:

Type type = Type.GetType(string.Format("Gestor.Data.Entities.{0}, Gestor.Data", e.Item.Value));
MetaDataUtil.GetColumnasGrid<type>();
Run Code Online (Sandbox Code Playgroud)

但它不起作用,你知道我怎么能这样做吗?

c# generics

10
推荐指数
1
解决办法
4537
查看次数

如何使用反射来获取泛型类型的扩展方法

从各种来源的teh interwebs我收集了以下功能:

public static Nullable<T> TryParseNullable<T>(this Nullable<T> t, string input) where T : struct
{
    if (string.IsNullOrEmpty(input))
        return default(T);

    Nullable<T> result = new Nullable<T>();
    try
    {
        IConvertible convertibleString = (IConvertible)input;
        result = new Nullable<T>((T)convertibleString.ToType(typeof(T), CultureInfo.CurrentCulture));
    }
    catch (InvalidCastException) { }
    catch (FormatException) { }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

我把它变成了一个扩展方法,如果我直接调用它就可以正常工作:

int? input = new int?().TryParseNullable("12345");
Run Code Online (Sandbox Code Playgroud)

当我尝试使用另一个泛型函数的上下文中的反射来调用它时,我的问题就出现了.SO充满了描述如何获得泛型方法和静态方法的MethodInfo的答案,但我似乎无法以正确的方式将它们组合在一起.
我已经正确地确定传递的泛型类型本身是泛型类型(Nullable<>),现在我想使用反射来调用TryParseNullable扩展方法Nullable<>:

public static T GetValue<T>(string name, T defaultValue)
{
    string result = getSomeStringValue(name);
    if (string.IsNullOrEmpty(result)) return defaultValue;

    try
    {
        if …
Run Code Online (Sandbox Code Playgroud)

c# generics reflection extension-methods

10
推荐指数
1
解决办法
5062
查看次数

是否有通用类使用静态方法的解决方法?

我有一个相当简单的问题,但在C#中似乎没有解决方案.

我有大约100个Foo类,每个类都实现一个static FromBytes()方法.还有一些泛型类应该使用这些方法FromBytes().但是泛型类不能使用这些static FromBytes()方法,因为它们T.FromBytes(...)是非法的.

我是否遗漏了某些内容或者无法实现此功能?

public class Foo1
{
    public static Foo1 FromBytes(byte[] bytes, ref int index)
    {
        // build Foo1 instance
        return new Foo1()
        {
            Property1 = bytes[index++],
            Property2 = bytes[index++],
            // [...]
            Property10 = bytes[index++]
        };
    }

    public int Property1 { get; set; }
    public int Property2 { get; set; }
    // [...]
    public int Property10 { get; set; }
}

//public class Foo2 { ... }
// …
Run Code Online (Sandbox Code Playgroud)

c# generics reflection

8
推荐指数
2
解决办法
476
查看次数

使用变量作为类型

是否可以使这些代码有效?:

    private List<Type> Models = new List<Type>()
    {
        typeof(LineModel), typeof(LineDirectionModel), typeof(BusStopTimeModel), typeof(BusStopNameModel)
    };

    foreach (Type model in Models) // in code of my method
    {
        Connection.CreateTable<model>(); // error: 'model' is a variable but is used like a type
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢

c#

8
推荐指数
1
解决办法
9992
查看次数

如何在T是动态的运行时从Entity-Framework获取ObjectSet <T>?

(注意,下面的代码只是示例.请不要评论为什么这是必要的.我希望肯定答案是或否,如果有可能那么如何?如果没有它也没关系.如果问题很模糊也让我知道.谢谢!)

例如,我可以在下面获得ObjectSet < T >:

ObjectSet<Users> userSet = dbContext.CreateObjectSet<Users>();
ObjectSet<Categories> categorySet = dbContext.CreateObjectSet<Categories>();
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常.但是,我需要实体表是动态的,所以我可以在类型之间切换.像下面的东西.

//var type = typeof(Users);
var type = typeof(Categories);
Object<type> objectSet = dbContext.CreateObjectSet<type>();
Run Code Online (Sandbox Code Playgroud)

但上面的代码将无法编译.

[编辑:]我想要的是类似的东西,或类似的东西:

//string tableName = "Users";
string tableName = "Categories";
ObjectSet objectSet = dbContext.GetObjectSetByTableName(tablename);
Run Code Online (Sandbox Code Playgroud)

asp.net entity-framework

7
推荐指数
2
解决办法
5895
查看次数

如何转换泛型类型以适合另一个泛型方法

我有一个A类方法

public IList<T> MyMethod<T>() where T:AObject
Run Code Online (Sandbox Code Playgroud)

我想在另一个泛型类B中调用此方法.此T没有任何约束.

public mehtodInClassB(){
    if (typeof(AObject)==typeof(T))
    {
      //Compile error here, how can I cast the T to a AObject Type
      //Get the MyMethod data
        A a = new A();
        a.MyMethod<T>();
    }
}
Run Code Online (Sandbox Code Playgroud)

C类继承自AObject类.

B<C> b = new B<C>();
b.mehtodInClassB() 
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

在提醒之后...更新:

是.我真正想做的是

typeof(AObject).IsAssignableFrom(typeof(T))
Run Code Online (Sandbox Code Playgroud)

typeof(AObject)==typeof(T))
Run Code Online (Sandbox Code Playgroud)

c# generics

7
推荐指数
1
解决办法
1351
查看次数

将类型传递给泛型方法(嵌套泛型)

如果我没有TRootEntity,我怎么能调用以下方法,但只有它TYPE:

public void Class<TRootEntity>(Action<IClassMapper<TRootEntity>> customizeAction) where TRootEntity : class;

最终目标是运行以下代码

var mapper = new ModelMapper();
mapper.Class<MyClass>(ca =>
{
    ca.Id(x => x.Id, map =>
    {
        map.Column("MyClassId");
        map.Generator(Generators.HighLow, gmap => gmap.Params(new { max_low = 100 }));
    });
    ca.Property(x => x.Something, map => map.Length(150));
});
Run Code Online (Sandbox Code Playgroud)

它用于创建动态NHibernate HBM.这里有更多信息

相关问题请参见此处此处.

c# nhibernate dynamic nhibernate-mapping

6
推荐指数
2
解决办法
2万
查看次数

如何在循环中设置Type类型的泛型变量?

我想通过调用不同类型的泛型方法在这样的循环中做一些类似的过程.

AAA,BBB都是班级.CreateProcessor是类中的通用方法MyProcessor.

new List<Type> {typeof (AAA), typeof (BBB)}.ForEach(x =>
{
    var processor = MyProcessor.CreateProcessor<x>(x.Name);
    processor.process();
});
Run Code Online (Sandbox Code Playgroud)

这不编译,我得到错误说Cannnot resolve symbol x.

从技术上讲,如何实现呢?(我知道策略模式更好......)

c# generics

6
推荐指数
2
解决办法
152
查看次数

函数返回一个泛型类型,其值仅在运行时已知

我需要使用如下通用接口:

public interface IContainer<T>
{
    IEnumerable<IContent<T>> Contents { get; }
}
Run Code Online (Sandbox Code Playgroud)

实现此接口的对象由以下通用方法返回:

IContainer<T> GetContainer<T>(IProperty property);
Run Code Online (Sandbox Code Playgroud)

T在运行时之前,类型是未知的.

使用反射我可以调用GetContainer<T>方法并获得结果.

我的问题是我不知道如何枚举具有类型的结果Object(因此我无法将其强制转换IEnumerable).

我也试过如下铸造,但它不起作用(它说"预期类型"):

var myContainer = genericMethodInfo.Invoke(
                           myService, 
                           new object[] { property })
    as typeof(IContainer<>).MakeGenericType(type);
Run Code Online (Sandbox Code Playgroud)

type运行时类型在哪里,myService是暴露GetContainer<T>方法的服务,并且propertyIProperty根据需要的类型.

更新:在我的博客中查看我的完整解决方案:http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/

c# generics reflection

5
推荐指数
0
解决办法
3269
查看次数