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

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

有没有一种方法来创建一个使用新()构造函数约束,要求使用特定类型的构造函数的类的一般方法?

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.

我使用通用的参数构造的解决方法是指定的构造为代表:

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); // ... }

然后调用时:

then when calling:

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

更多推荐

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

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

发布评论

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

>www.elefans.com

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