C# 泛型方法,new() 构造函数约束中的类型参数

编程入门 行业动态 更新时间:2024-10-26 08:22:36
本文介绍了C# 泛型方法,new() 构造函数约束中的类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有办法创建一个通用方法,它使用 new() 构造函数约束来要求具有特定类型构造函数的类?

Is there a way to create a Generic Method that uses the new() constructor constraint to require classes with constructors of specific types?

例如:

我有以下代码:

public T MyGenericMethod<T>(MyClass c) where T : class { if (typeof(T).GetConstructor(new Type[] { typeof(MyClass) }) == null) { throw new ArgumentException("Invalid class supplied"); } // ... }

有没有可能有这样的东西?

Is it possible to have something like this instead?

public T MyGenericMethod<T>(MyClass c) where T : new(MyClass) { // ... }

关于此的建议.请投票,以便我们可以在 C# 中使用此功能!

There's a suggestion regarding this. Please vote so we can have this feature in C#!

推荐答案

不是真的;C# 仅支持无参数构造函数约束.

Not really; C# only supports no-args constructor constraints.

我用于泛型 arg 构造函数的解决方法是将构造函数指定为委托:

The workaround I use for generic arg constructors is to specify the constructor as a delegate:

public T MyGenericMethod<T>(MyClass c, Func<MyClass, T> ctor) { // ... T newTObj = ctor(c); // ... }

然后在调用时:

MyClass c = new MyClass(); MyGenericMethod<OtherClass>(c, co => new OtherClass(co));

更多推荐

C# 泛型方法,new() 构造函数约束中的类型参数

本文发布于:2023-11-02 15:11:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   类型   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!