c# - 对泛型和类型有点困惑

标签 c#

我想做这样的事情(大大简化的代码):

public class MyClass 
{

   private Type _listingType = typeof(AntiqueSellerListing);

   public DeleteEntity(int id) 
   {
       // This is what I would like to do, but it does not compile
       SystemLogic.DeleteItem<this._listingType>(id);

       // But this does
       SystemLogic.DeleteItem<AntiqueSellerListing>(id);
   }    
}

DeleteItem 方法定义如下:

public void DeleteItem<T>(int primaryKeyValue) where T : class

我可能在这里遗漏了一些简单的东西,但我不确定如何做我想做的事情。

最佳答案

该类型必须是编译时表达式,以便运行时可以生成该方法的代码。这是因为运行时无法保证在生成代码之前定义变量。例如,Ngen 工具允许在不运行任何代码的情况下预编译代码。

关于c# - 对泛型和类型有点困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17501829/

相关文章:

c# - 此代码中是否存在任何性能问题

c# - 将字符串拆分为 GUID 数组

c# - 使用javascript查找放置在gridview中的复选框和文本框

c# - 如何在具有指定数据源的 DataGridView 中启用排序?

c# - 维护安全的 MySQL 连接

c# - 具有 Observable 的复杂流程

javascript - 添加/删除 CSS 类属性以尊重不基于 Div id 的类

c# - 如何修复 Visual Studio 2015 中的错误 "Could not load file or assembly ' Microsoft.VisualStudio.Web?

c# - 使用 MD5 或 sha-256 C# 散列密码

c# - : "save picture as" in IE for an image retrieved from database via an image handler 的问题