可以说,如果我有如下情况.
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)
如何在编译时不知道类型的情况下调用泛型函数?
我正在尝试执行一个返回 T 类型对象的扩展方法,但我正在尝试基于 Header/Detail 动态泛型类型使类型 T 动态化。
这可能有点冗长...
using System;
using System.Collections.Generic;
namespace Blah
{
public interface IHeader
{
string Name { get; set; }
IDetail Detail { get; set; }
}
public interface IDetail
{
//Nothing the 'Real' implementation of this
//interface will have it's own properties.
}
public class GenericHeader : IHeader
{
public string Name { get; set; }
public IDetail Detail { get; set; }
}
public class RealHeader : GenericHeader
{
public new RealDetail Detail …Run Code Online (Sandbox Code Playgroud) 我曾经使用下面的代码将JSON文本反序列化为强类型对象
Trainer myTrainer = JsonConvert.DeserializeObject<Trainer>(sJsonText);
Run Code Online (Sandbox Code Playgroud)
现在我需要将反序列化JSON文本转换为特定类型,只知道类型的名称.
我尝试使用Reflection从其名称中获取Type,然后将此类型与JsonConvert一起使用,如下所示:
Type myType = Type.GetType("Trainer");
var jobj = JsonConvert.DeserializeObject<myType >(sJsonText);
Run Code Online (Sandbox Code Playgroud)
但不幸的是,下面的错误显示出来:
CS0118 'myType' is a variable but is used like a type
Run Code Online (Sandbox Code Playgroud)
有没有办法可以使用字符串引用类?
我有一些类似的代码:
Lookup(Of String)("Testing")
Lookup(Of Integer)("Testing")
Run Code Online (Sandbox Code Playgroud)
这些查找都很好用。我要尝试的是根据另一个变量的类型调用适当的LookUp。看起来像...
Lookup(Of GetType(MyStringVariable))("Testing")
Run Code Online (Sandbox Code Playgroud)
我尝试使用Google进行搜索,但是很难找到合适的搜索。谁能告诉我该怎么做?
我得到了Type,但这与我正在寻找的Class不同.
是否存在typeof的逆操作?
我需要该类才能使用通用存储库:
GenericRepository<BaseEntity> repository = new GenericRepository<BaseEntity>(new AzureBrightData());
Run Code Online (Sandbox Code Playgroud)
我从编写BaseEntity开始,所有实体类都从该BaseEntity下降,但问题是存储库需要知道要搜索的表.
例如,如果我们有(1,1)的分区键和行键组合对,则不允许我或存储库知道从哪个表获取注册表.这还不够,这就是我相信我需要桌子的原因.
在下面的示例中,是否可以动态设置Classname类型参数?
UpdateAndSave<Classname>>().Execute(sql)
Run Code Online (Sandbox Code Playgroud) 假设我有两种类似的方法:
public List<object> Do<T>(Stream stream)
{
... does cool things
}
public List<object> Do(Type type, Stream stream)
{
T = type // <- what should this be
return Do<T>(Stream);
}
Run Code Online (Sandbox Code Playgroud)
什么是允许它按预期运行的代码?
我想这个问题必须在这里复制一些东西,但我找不到我的google-fu.
我怎么能做这样的事情?我发现如何使用反射来调用泛型方法?但不确定这是我的情况.
public class XmlSerializer
{
public string Serialize<T>(T obj) where T : class
{
return string.Empty;
}
}
class Program
{
static void Main(string[] args)
{
MakeRequst<string>("value");
}
public static void MakeRequst<T>(T myObject)
{
var XmlSerializer = new XmlSerializer();
XmlSerializer.Serialize<T>(myObject);
}
}
Run Code Online (Sandbox Code Playgroud) 所以我在C#中构建一个小应用程序,我有一个IEnumerable,我想把它转换成List.这就是我得到的:
var enumerable = SettingsManager.ReadSettings();
var list = enumerable.Cast<Setting>().ToList();
Run Code Online (Sandbox Code Playgroud)
编译器说无法从使用中推断出ReadSettings.这就是ReadSettings的样子:
public static IEnumerable<T> ReadSettings<T>()
{
//Code omitted
return JsonConvert.DeserializeObject<T[]>(fileAsString).ToList<T>();
}
Run Code Online (Sandbox Code Playgroud) 给出以下接口:
interface IEntity
{
int Id{get;}
}
interface IPerson : IEntity
{
string Name{get;}
int Age{get;}
}
interface ITeacher : IPerson
{
string StaffId{get;}
}
interface IStudent : IPerson
{
string StudentId{get;}
string Courses{get;}
}
interface IRepository
{
T Get<T>(int id) where T : IEntity
}
Run Code Online (Sandbox Code Playgroud)
我的命名空间中有以下类
public class EntityBase() : IEntity
{
int Id{get;set;}
}
public class Teacher : EntityBase, ITeacher{}
public class Sudent : EntityBase, IStudent{}
Run Code Online (Sandbox Code Playgroud)
目前我正在实现这个IRepository,如下所示:
class Repository: IRepository
{
IDataContext Context{get;set;}
T Get<T>(int id) where T …Run Code Online (Sandbox Code Playgroud) 我正在使用.Net framework 2.0来尝试执行以下操作:
我有一个返回int列表的外部服务.反过来,我使用每个int来查找具有属性的相应Type,其中包含属性key; 该属性的值与搜索参数匹配.
使用Type tI想调用泛型方法,但我无法做到这一点.因为我只会在运行时知道Type,我怀疑我可能不得不使用反射来调用泛型方法GetResultsForType- 这是正确的方法吗?
[MyAttribute(key1 = 1)]
class A{
//some properties
}
[MyAttribute(key1 = 2)]
class B{
//some properties
}
//and so on (for hundreds of classes). The key is unique for every class.
public class Foo{
public void DoSomething(){
IList<int> keys = QuerySomeExternalService();
Assembly asm = LoadAssemblyFromSomewhere();
Type[] types = asm.GetTypes();
foreach(int key in keys){
Type t = SearchTypesForAttributeWithMatchingKey(types, key); //I omitted caching of all the keys and Types into a Dictionary …Run Code Online (Sandbox Code Playgroud) 好的简短背景.我正在尝试各种方法来测试API,并且我试图允许用户提供API调用的简单CSV文件,我的测试框架可以使用通用测试方法进行迭代.我无法将类型传递给我的通用API调用方法.请允许我演示.
鉴于我有一个具有以下基本结构的方法
public T GetData<T>(Uri uri, HttpStatusCode expectedStatusCode)
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
myHttpWebRequest.Accept = "application/json";
var response = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (response.StatusCode != expectedStatusCode)
Report.Log(ReportLevel.Failure, "ExpectedResponseCode:" + expectedStatusCode.ToString() + " ActualResponseCode:" + response.StatusCode.ToString());
string responseString = "";
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream, Encoding.UTF8);
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
Run Code Online (Sandbox Code Playgroud)
我可以毫无问题地将上述内容如下调用
Person person = _apiHelper.GetData<Person>(uri, HttpStatusCode.Ok);
Run Code Online (Sandbox Code Playgroud)
但是假设我现在有一个我已经获得的类型,如下所示
Type returnType = Type.GetType(typeString, true, true);
Run Code Online (Sandbox Code Playgroud)
为什么我不能按如下方式调用GetData方法
var result = _apiHelper.GetData<returnType>(uri, HttpStatusCode.Ok);
Run Code Online (Sandbox Code Playgroud)
Visual Studio简单地说它无法解决这个问题