开发者

how to pass a converter (constraints not applicable for generic arguments)

I want to pass a converter to a method, and the constraint must be that the converter always gets a string as argument. I tried the following, but it won't compile:

class Test
{
   public void Foo(string val, Converter<Tin,Tout> conv)
        where Tin:string
   {
      myObj = conv(val);
开发者_StackOverflow中文版   }
}


What's the point of constraining Tin if it's always going to be a string?

class Test 
{ 
   public void Foo<Tout>(string val, Converter<string,Tout> conv) 
   { 
      myObj = conv(val); 
   } 
} 

Just get rid of the Tin type and use string in your Converter. I think you're over-complicating things.

You cannot use string as a generic constraint as it's a sealed class. This makes perfect sense as nothing can inherit from string so why add a constraint for string?

I.e. If you COULD inherit from string:

public SuperString : string

Then you could use string as a constraint and pass through SuperString as Tin. However you CANNOT do this as string is a sealed class. Therefor the only object you could pass to Tin is String anyway.

Because of this, you may as well get rid of Tin and use the code I wrote above.


Whenever a function signature should carry a generic argument, or an argument with a generic type parameter, that type parameter must be part of the method declaration and the method becomes generic itself.

Especially, the generic type arguments you want to constrain must be part of the method signature of Foo.

Try it this way:

class Test 
{ 
   public void Foo<Tout>(string val, Converter<string, Tout> conv) 
   { 
      myObj = conv(val); 
   } 
} 


Your code nonsensical.

where Tin:string is not valid. Fix that, and add the generic parameters to your method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜