Setting generic type at runtime

后端 未结 6 1257
无人共我
无人共我 2020-11-27 18:24

I have a class

public class A
{
   public static string B(T obj)
   {
       return TransformThisObjectToAString(obj);
   }
}

The

6条回答
  •  隐瞒了意图╮
    2020-11-27 18:48

    You can't. But you've asked the wrong question for the case provided. In this case (as in 99% of cases) all you actually need is a type constraint.

    Try:

    public class A where T : object
    

    or, if T is a known class, a subclass, or an interface then it would be better to use

    public class A where T : YourAbstractClass
    

    Other type constraints also exist. More details: http://msdn.microsoft.com/en-us/library/d5x73970(VS.80).aspx

    As a general note, when learning a new language, you often have to think broadly about what you want to achieve, not specifically finding what you want to do. This is much like real-world verbal languages. It's the difference between learning German by reading a dictionary and forcing the words into English syntax, or learning the syntax and picking up the words. Yes, a German speaker will understand someone who is speaking out of a dictionary, but the WTF per sentence count will be much higher.

提交回复
热议问题