Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it not supported, is it supported but I have to do some tricks?

Example:

class Foo
{
  public Foo<T1,T2>(Func<T1,T2> f1,Func<T2,T1> f2)
  {
     ...
  }
}

the generics are only used in constructor, there is no field/property depended on them, I use it (generics) to enforce the type correlation for f1 and f2.

Remark: I found the workaround -- static method Create, but anyway I am curious why I have problem with straightforward approach.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

No, generic constructors aren't supported in either generic or non-generic classes. Likewise generic events, properties and finalizers aren't supported.

Just occasionally I agree it would be handy - but the syntax would look pretty awful. For example, suppose you had:

public class Foo<T> {}

public class Foo
{
    public Foo<T>() {}
}

What would

new Foo<string>()

do? Call the generic constructor of the non-generic class, or the normal constructor of the generic class? You'd have to differentiate between them somehow, and it would be messy :(

Likewise, consider a generic constructor in a generic class:

public class Foo<TClass>
{
    public Foo<TConstructor>() {}
}

How would you call the constructor? Hopefully we can all agree that:

new Foo<string><int>()

is pretty hideous...

So yes, semantically it would be occasionally useful - but the resulting ugliness counterbalances that, unfortunately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...