使用Activator.CreateInstance()时为空 [英] Null when using Activator.CreateInstance()

查看:360
本文介绍了使用Activator.CreateInstance()时为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。



我有这段代码和扩展方法:



< pre lang =cs> class 计划
{
public static TestClass TestClass { get ; set ; }

静态 void Main( string [] args)
{
TestClass.New< TestClass>();
}
}

class TestClass
{

}

static class ObjectExtensions
{
public static T New< T>( T实例)
{
instance = Activator.CreateInstance< T>();
return (T)实例;
}
}





TestClass属性为空。



有人可以解释为什么这是空的吗?



上下文:基本上我想创建一个扩展方法来创建任何类型的新实例:

此方法将取代传统的TestClass = new TestClass();



非常感谢



Charles

解决方案

扩展方法按值传递,因此在方法中设置 instance 不执行任何操作。您可以像这样分配返回的值:



 静态  void  Main( string  [] args)
{
TestClass = TestClass.New< TestClass> ;();
}





但你为什么要这样做而不是只使用新的?


嘿谢尔比

为那个队友干杯:我不知道扩展方法仅通过值传递。



我背后的理由:只是试图看看是否能够支撑新的TestClass();



还有很多其他方法,但想尝试使用扩展方法。


Hi all.

I have this piece of code and an extension method:

class Program
   {
       public static TestClass TestClass { get; set; }

       static void Main(string[] args)
       {
           TestClass.New<TestClass>();
       }
   }

   class TestClass
   {

   }

   static class ObjectExtensions
   {
       public static T New<T>(this T instance)
       {
            instance = Activator.CreateInstance<T>();
            return (T)instance;
       }
   }



TestClass property is null.

Could someone please explain why this is null?

Context: Basically I want to create an extension method to create a new instance of any type:
This method will replace the coventional TestClass = new TestClass();

Much appreciated

Charles

解决方案

Extension methods pass by value, so setting instance in the method does nothing. You can assign the returned value like this:

static void Main(string[] args)
{
    TestClass = TestClass.New<TestClass>();
}



but why would you want to do that as opposed to just using new?


Hey Shelby
Cheers for that mate: I wasn''t aware that extension methods pass by value only.

My reasoning behind it: was just trying to see if could shoreten the new TestClass();

There tons of other ways but wanted to try with extension methods.


这篇关于使用Activator.CreateInstance()时为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆