开发者

How do you make this parameter access syntax possible?

开发者 https://www.devze.com 2023-02-16 06:29 出处:网络
public class SampleClass { public int value; public SampleClass(int v) { value = v; } } // i want to access value like this
public class SampleClass {
     public int value;

     public SampleClass(int v)
     { value = v; }
}

// i want to access value like this
SampleClass sc = new SampleClass(5);

int i = sc;

Is there a wa开发者_开发知识库y to do this in C#? I don't want to have to say sc.Value every time i need to access the value.


Use an implicit conversion:

public class SampleClass {
     public int value;

     public SampleClass(int v)
     { value = v; }

     public static implicit operator int (SampleClass c)
     {
       return c.value;
     }
}

You should look into properties however.


You can do it by including an implicit conversion from SampleClass to int:

public static implicit operator int(SampleClass s)
{
    return s.value;
}

... but I would strongly recommend that you don't do so, or at least that you think very carefully beforehand. Implicit conversions make it harder to reason about the language in various ways (consider things like overload resolution, for example).

Very, very occasionally it's a good idea to introduce implicit conversions - for example LINQ to XML makes great use of it with string to XNamespace and string to XName conversions - but I wouldn't do it here just to avoid having to use .Value.

It's slightly more reasonable to make an explicit conversion (just change implicit to explicit in the operator conversion) in that at least that makes it clear-ish what's going on in the calling code... but at that point there's really not much difference in source size between a cast to int and using .Value.

(And as suggested elsewhere, don't make fields public - use properties instead.)


Take a look at this. You need to overload the implicit cast operator for int.


Yes, it's possible. You need to implement implicit for your SampleClass: Here it is:

public class SampleClass
{
  public int Value;
  public SampleClass(int v)
  {
    Value = v;
  }

  public static implicit operator int(SampleClass d)
  {
    return d.Value;
  }
}
0

精彩评论

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

关注公众号