首页 \ 问答 \ C#键入Generic类(C# Type to Generic class)

C#键入Generic类(C# Type to Generic class)

我有一个MVC C#代码优先的项目。 我想将一个类型传递给我的方法。 我的方法需要一个类来工作。 但我不想通过课 - 我希望它是动态的。 有可能吗?

这是我的代码;

string item ="PERSON" // item is a parametric I give the table name to get the type of table 
Assembly asm = Assembly.Load("ProjectName");
Type entityType = asm.GetType(String.Format("NameSpace.Model.{0}", item));

 var test = LINQDynamic<>.GetQueryResult(ssa,entityType,ddd); // In LINQDynamic<> I want to use entityType like that LINQDynamic<entityType> but it's not acceptable what can I make the convert type to generic?..Because table name is parametric.Is it possible to convert that type?

public class LINQDynamic<TEntity> where TEntity: class
   {

       public static object GetQueryResult(object pkKey,Type type, params object[] pkKeys)
       {
                     //TODO
       }
    }

I have a project in MVC C# code-first. I want to pass a type to my method. And my method needs a class to work. But I don't want to pass a class - I want it to be dynamic. Is it possible or not?

Here is my codes;

string item ="PERSON" // item is a parametric I give the table name to get the type of table 
Assembly asm = Assembly.Load("ProjectName");
Type entityType = asm.GetType(String.Format("NameSpace.Model.{0}", item));

 var test = LINQDynamic<>.GetQueryResult(ssa,entityType,ddd); // In LINQDynamic<> I want to use entityType like that LINQDynamic<entityType> but it's not acceptable what can I make the convert type to generic?..Because table name is parametric.Is it possible to convert that type?

public class LINQDynamic<TEntity> where TEntity: class
   {

       public static object GetQueryResult(object pkKey,Type type, params object[] pkKeys)
       {
                     //TODO
       }
    }

原文:https://stackoverflow.com/questions/32985220
更新时间:2022-02-26 07:02

最满意答案

尽管你可以使用嵌套的条件表达式来做到这一点,但我建议不要这样做:即使只有一个条件表达式,表达式也是不可读的,更不用说两个或三个嵌套的表达式。

使用私有静态成员函数对于此任务来说是一个不错的选择:函数可以“解析” foo的值,并决定要返回的正确对象:

Child::Child(const std::string & foo)
:   Parent(constructParentArgs(foo)) {
}
private static someClassPtr *constructParentArgs(const std::string& foo) {
    if (foo == "x") return someClassPtr(new someClass());
    if (foo == "y") return someClassPtr(new someOtherClass());
    if (foo == "z") return someSubClassPtr(new yetAnotherClass());
    // provide a default value here
    return someClassPtr(new defaultClass());
}

这种方法对于代码的读者的优点是,他们不必为调用父构造函数的细节而烦恼,除非他们想看看发生了什么。 当他们读取标题时,他们都知道你的代码以某种方式创建了父参数。 如果他们想要了解参数的构造方式,他们总是可以直接进入私有成员函数。


Although you can definitely do it with nested conditional expressions, I would recommend against it: the expression borders on non-readable even with a single conditional, let alone two or three nested ones.

Using a private static member function would be a good choice for this task: the function could "parse" the value of foo, and decide on the proper object to return:

Child::Child(const std::string & foo)
:   Parent(constructParentArgs(foo)) {
}
private static someClassPtr *constructParentArgs(const std::string& foo) {
    if (foo == "x") return someClassPtr(new someClass());
    if (foo == "y") return someClassPtr(new someOtherClass());
    if (foo == "z") return someSubClassPtr(new yetAnotherClass());
    // provide a default value here
    return someClassPtr(new defaultClass());
}

The advantage of this approach for the readers of your code is that they do not have to bother themselves with the details of calling the parent constructor, unless they want to see what is going on. When they read the header, all they know that your code somehow creates parent argument. If they want to learn how exactly the argument gets constructed, they can always go straight to the private member function.

相关问答

更多
  • 您可以很容易地跳过第一个值: for x,y in enumerate(b[1:]): # adding + 1 where value is 1 if y != 0: b[x + 1] += b[x] b[1:]只是从列表中跳过枚举的第一个值。 这样第一个数字就不会受到影响。 但是因为x中的索引现在都太低了,我们必须在两种情况下都添加一个,将x转换为x + 1 ,将x - 1转换为x 。 这样我们就可以访问正确的索引。 使用您的测试列表,它产生以下输出: [1, 0, 0, 1, ...
  • 你理解错了。 它们可以在类定义*之外的单个转换单元中初始化,并且可以在构造函数中分配它们。 您只能在构造函数的初始化列表中初始化当前的非static类成员。 *例外情况适用 You got it wrong. They can be initialized in a single translation unit outside the class definition* and they can be assigned to in the constructor. You can only initial ...
  • 我认为你把赋值和声明搞混了。 你可以做 public static void main(String[] args){ String h = null; for(int i=7,k=999;i+((h="hello").size())<10;i++){} System.out.println("It should be: hello = "+h); } =的运算符是正确的关联,并将第一个参数设置为第二个参数并计算为第一个参数,所以类似 a = b = c = 4 是相同的 (a ...
  • 是。 只要不直接或间接访问未初始化的成员或虚拟函数 ,因为对象尚未完全构建,就可以使用this指针在初始化列表中 。 对象child可以存储this Parent指针,供以后使用! Yes. It's safe to use this pointer in initialization-list as long as it's not being used to access uninitialized members or virtual functions, directly or indirectly ...
  • 这句话充满了危险 。 my $object = $test ? undef : Class::create($args); my $object; $object = Class::create($args) unless $test; 是更安全的替代品。 That syntax is ... fraught with peril. my $object = $test ? undef : Class::create($args); my $object; $object = Class::creat ...
  • 在第一种形式中,首先独立地引用x 。 与第二种形式不同, x需要先定义,否则会引发错误。 > x = nil => nil > x || x = 10 => 10 形式x ||= 10将声明和测试结合起来,因此无论x是否已经被声明,它都不会产生错误。 In the first form, x is referenced first independently. Unlike the second form, x needs to be defined first or else it would rais ...
  • 为什么我们应该为基类型而不是常用区域(-1)使用列表初始化? 首先,我认为那里的信息只是在可以使用时应该使用C ++ 11的统一初始化。 在这种情况下,它主要是风格和品味的问题。 作者提倡的风格和品味是否会成为事实上的标准,目前很难说清楚。 我们都知道统一初始化毕竟不是那么统一。 另一方面,在大多数情况下,采用它作为默认编码风格的好处是吸引人的 - 句法一致性,以及诸如最令人烦恼的解析之类的问题消失的事实。 这就是说,当初始化列表只包含一个元素时,初始化的对象从该元素初始化(第8.5.4 / 3节)。 这使 ...
  • ...或POD类类型或POD类类型的数组,它们直接或间接包含一个const限定成员。 但是,是的,你的主要案件。 对于你的(3),只有在用户声明的构造函数不是默认构造函数时才适用。 如果根本没有用户声明的构造函数,那么如果初始化程序列表中没有提及该成员,则该成员可以被默认初始化。 ...or POD class types or arrays of POD class types that directly or indirectly themselves contain a const-qualified ...
  • 不管怎么说,这不会编译,我不认为。 但无论哪种方式,如果你没有初始化它,该值将获得int的默认值。 相当于: int? var1 = null; int var2 = 2; int var3 =5; var t = new Test { Test1 = var1.GetValueOrDefault(), Test2 = var2, Test3 = var3 }; That wouldn't compile a ...
  • 尽管你可以使用嵌套的条件表达式来做到这一点,但我建议不要这样做:即使只有一个条件表达式,表达式也是不可读的,更不用说两个或三个嵌套的表达式。 使用私有静态成员函数对于此任务来说是一个不错的选择:函数可以“解析” foo的值,并决定要返回的正确对象: Child::Child(const std::string & foo) : Parent(constructParentArgs(foo)) { } private static someClassPtr *constructParentArgs(con ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)