我需要在运行时创建一个使用泛型的类的实例,比如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#中写入一个类型变量.还有另一种方法吗?
我正在尝试这样做:
Type type = Type.GetType(string.Format("Gestor.Data.Entities.{0}, Gestor.Data", e.Item.Value));
MetaDataUtil.GetColumnasGrid<type>();
Run Code Online (Sandbox Code Playgroud)
但它不起作用,你知道我怎么能这样做吗?
从各种来源的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#中似乎没有解决方案.
我有大约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) 是否可以使这些代码有效?:
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)
提前致谢
(注意,下面的代码只是示例.请不要评论为什么这是必要的.我希望肯定答案是或否,如果有可能那么如何?如果没有它也没关系.如果问题很模糊也让我知道.谢谢!)
例如,我可以在下面获得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) 我有一个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) 如果我没有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.这里有更多信息
我想通过调用不同类型的泛型方法在这样的循环中做一些类似的过程.
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.
从技术上讲,如何实现呢?(我知道策略模式更好......)
我需要使用如下通用接口:
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>方法的服务,并且property是IProperty根据需要的类型.
更新:在我的博客中查看我的完整解决方案:http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/