0

im know a lot in php, but im newbie in asp.net.

In asp.net exists magic methods in classes like php?(__construct(), __isset() __get() __set() __destruct(), etc) for example, how i can do this in asp.net c#:

class foo
{
    public $name;

    public function __contruct($name){
        $this->name = $name;
    }

    public function getName(){
        return $name;
    }
}

$test = new Foo("test");
echo $test->getName(); //prints test

Thanks for help!

4

3 に答える 3

9

If you were really missing your magic methods, you could create a dynamic base class in C# (provided you are using .NET 4.0+):

    public abstract class Model : DynamicObject
{
    public virtual object __get(string propertyName)
    {
        return null;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if ((result = this.__get(binder.Name)) != null)
            return true;
        return base.TryGetMember(binder, out result);
    }

    public virtual void __set(string propertyName, object value)
    {
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        this.__set(binder.Name, value);
        return true;
    }
}

Create a new type derived from that and instantiate using "dynamic" keyword:

dynamic myObject = new MyModelType();

myObject.X = 42;  //  calls __set() in Model
Console.WriteLine(myObject.X); //  calls __get() in Model

In short you could achieve very similar behavior in C# if you wanted to (see DynamicObject on MSDN).

于 2015-08-14T07:44:21.307 に答える
0
class Foo
{
    private string name;  //don't use public for instance members

    public Foo(string name){
        this.name = name;
    }

    public string getName
    {
      get{
        return this.name;
      }
    }
}

Foo test = new Foo("test");

Console.WriteLine(test.getName);
  • In C#, Constructor is a function with the same name as the class name with no return type

  • You precede variables with their data type e.g. int x, string y or var xyz;

  • There is no getter/setter method like in Java/PHP, it uses property. So there won't be getXXX() or setXXX() for properties. Here is how you set property

Example

string _name;
public string Name
{
    get { return _name; }
    set { _name = value; }
}

//Usage

Foo f = new Foo();
f.Name = "John";
string name = f.Name;
于 2012-10-21T20:44:43.633 に答える
-1

The equivalent in C# would be someting like this:

public class Foo
{
  public string Name { get; set; }

  public Foo(string name)
  {
    Name = name;
  }

  public string GetName()
  {
    return Name;
  }
}

var test = new Foo("test");
Console.WriteLine(test.GetName());

As you can see there is "magic" in C#. I've helped get you started so now you can go learn C#.

于 2012-10-21T20:42:00.720 に答える