使用语句处理对象越来越出错 [英] disposing object by using statement is getting error

查看:101
本文介绍了使用语句处理对象越来越出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using (UserProfile objProf = new UserProfile())
           {

               objProf.UserName = txtYourName.Text;
               objProf.UserEmail = txtEmail.Text;
               objProf.UserPhone = txtPhone.Text;

               if (rbtnMale.Checked == true)
               {
                   objProf.UserGender = "M";
               }
               else if (rbtnFemale.Checked == true)
               {
                   objProf.UserGender = "F";
               }
               int Result = new UserProfileBAL().InsertBasicUserProfile(objProf);
           }




我正在使用以下代码来放置对象..但是在关键字附近出现了以下错误:使用


错误消息:




i am using the following code to dispose the object.. but i am getting the following error near keyword :Using


error msg:

Error   3   'UserProfile': type used in a using statement must be implicitly convertible to 'System.IDisposable'

推荐答案

类型必须隐式转换为"System.IDisposable"
错误本身是不言而喻的.

using语句旨在确保在using块的末尾处置对象,因此,此类语句只能使用可抛弃的类型.
此处的详细信息:编译器错误CS1674 [
type used in a using statement must be implicitly convertible to ''System.IDisposable''
Error in itself is self explanatory.

The using Statement is intended to be used to ensure the disposal of an object at the end of the using block, thus, only types which are disposable may be used in such a statement.
Details here: Compiler Error CS1674 [^]

You need to do implement IDisposable interface for your UserProfile class, something like:
// OK
class D : IDisposable {
   void IDisposable.Dispose() {}
   public void Dispose() {}

   public static void Main() {
      using (D d = new D()) {}
   }
}


public class UserProfile : System.IDisposable
{
   public UserProfile()
   {
  
   }
   public void Close()
   {

   }
}



现在,您可以从using语句中调用UserProfile类!:)



Now you can call the UserProfile class from a using Statement!:)


using语句将查看表达式的最终类型,即从UserProfile()返回的所有内容;如果这返回的是IDisposable的东西,那么您就可以了.如果错误,编译器会告诉您.

作为一个简单的步骤,请确保添加了正确的库引用以对其进行修复.例如,在LInQ代码中,如果您错过通过类似的使用"模型添加对System.Data.Entity的引用,则将得到相同的错误.
The using statement will look at the final type of the expression i.e. whatever is returned from UserProfile(); if this returns something that is IDisposable, then you''re OK. The compiler will tell you if you get it wrong.

As a simple step, make sure that you added the proper library reference to fix it. As an example, in LInQ code, if you miss to add a reference to System.Data.Entity thro similar ''using'' model, then you will get the same error.


这篇关于使用语句处理对象越来越出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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