当在编译时未知类型参数但是在运行时动态获取时,调用泛型方法的最佳方法是什么?
考虑以下示例代码 - 在Example()方法内部,GenericMethod<T>()使用Type存储在myType变量中调用的最简洁方法是什么?
public class Sample
{
public void Example(string typeName)
{
Type myType = FindType(typeName);
// What goes here to call GenericMethod<T>()?
GenericMethod<myType>(); // This doesn't work
// What changes to call StaticMethod<T>()?
Sample.StaticMethod<myType>(); // This also doesn't work
}
public void GenericMethod<T>()
{
// ...
}
public static void StaticMethod<T>()
{
//...
}
}
Run Code Online (Sandbox Code Playgroud) 我是C#的新手,并直接潜入修改我收到的项目的一些代码.但是,我一直看到这样的代码:
class SampleCollection<T>
Run Code Online (Sandbox Code Playgroud)
而我无法弄清楚是什么
<T>
Run Code Online (Sandbox Code Playgroud)
意味着什么也不称之为.
如果有人愿意帮我说出这个概念的名称,我可以在线搜索.但是,到目前为止我还是一无所知.
我需要在运行IEnumerable<IEnumerable<T>>时才知道T.
我已经建立了我的收藏品:
new List<List<object>>()
Run Code Online (Sandbox Code Playgroud)
内部列表中的所有对象都是a T
但是,由于CO /逆变的(永远记住它是!)我List的List小号心不是一个IEnumerable的IEnumerable秒.
我该怎么办?
我已经尝试使用Convert.ChangeType,但它的呻吟声是List不是IConvertible
线索:阅读问题.再次.我说我只T在运行时知道.
private static void GetData()
{
dynamic dynamicList =FetchData();
FilterAndSortDataList(dynamicList);
}
private static void FilterAndSortDataList<T>(List<T> dataList)
{
...
}
Run Code Online (Sandbox Code Playgroud)
调用FilterAndSortDataList时出现运行时绑定错误。有没有办法List<T>在运行时将我的dynamicList强制转换为?
请注意,FetchData()包含在插件中,所以我事先不知道T是什么类型。
我创建了一个通用类来将一些数据解析成另一个类(MyClass1)的实例.由于MyClass1只有内置的C#类型,我的GenericMethod工作正常.当MyClass1有另一个MyClass2属性时问题开始增长,我仍然想调用我GenericMethod来解析我的数据.
我无法在其范围内触发我的Generic Class方法,因为我需要更改其类型T.有什么方法可以解决这个问题吗?
public class MyClass1
{
public int MyIntProperty { get; set; }
public string MyStringProperty { get; set; }
public MyClass2 MyClass2Property { get; set; }
}
public class MyClass2
{
public int MyOtherIntProperty { get; set; }
public string MyOtherStringProperty { get; set; }
public bool MyOtherBoolProperty { get; set; }
}
public class MyGenericClass<T> where T : class
{
public static T …Run Code Online (Sandbox Code Playgroud) 可以说,如果我有如下情况.
Type somethingType = b.GetType();
// b is an instance of Bar();
Foo<somethingType>(); //Compilation error!!
//I don't know what is the Type of "something" at compile time to call
//like Foo<Bar>();
//Where:
public void Foo<T>()
{
//impl
}
Run Code Online (Sandbox Code Playgroud)
如何在编译时不知道类型的情况下调用泛型函数?