This is the way properties are defined in C# language.
In C# unlike in PHP, class properties are not simple variables and when you set or get their values, accessor functions are called. So you can lock a property from being changed after initialization. In php it seems without function name followed by parentheses you can't call such value. Is there any similar concept in PHP for that?
Not yet, but "maybe" in future versions of PHP.
RFC: https://wiki.php.net/rfc/propertygetsetsyntax
Magic _get/_set and "overloading", are various cases of code smell.
It's possible to have get and set methods in PHP using the __get and __set magic methods (though the implementation is different from C#)
class A {
protected $test_int;
function __construct() {
$this->test_int = 2;
}
function __get($prop) {
if ($prop == 'test_int') {
echo 'test_int get method<br>';
return $this->test_int;
}
}
function __set($prop, $val) {
if ($prop == 'test_int') {
echo 'test_int set method<br>';
//$this->test_int = $val;
}
}
}
$obj = new A();
$obj->test_int = 3; //Will echo 'test_int set method'
echo $obj->test_int; //Will echo 'test_int get method' and then the value of test_int.
If you want to "lock" a property's value, simply do:
function __set($prop, $val) {
if ($prop == 'test_int') {
//Do nothing
}
}
I don't understand what you are meaning.
But if you'r talking about getters and setters, you can simply declare your var as private and make a public method to get the value.
private $lol;
public getlol(){
return $this->lol;
}
But if you'r talking about contants you need try it:
define("MAXSIZE", 100);
Related
We use ClearScript to extend our apps. We expose various C# objects into JavaScript, using ClearScript's AddHostType and AddHostObject methods.
Recently we've started using Typescript in our Google Apps Script projects and thought it would be good to use it to manage our ClearScript scripts as well.
This has proved to be an interesting experience. We know know about such things as external.d.ts and have started to write one to handle the various symbols that we're injecting in from the C# side.
Some things we've been able to work out. For example, in this code
function SchTasks(instruction:string) {
var proc = CSProcess.Start("C:\\Windows\\System32\\schtasks.exe", instruction);
return proc;
}
this declaration seems to work
declare namespace CSProcess {
function Start(a:string, b:string): any;
}
Likewise, with this block
that.getMyIP = function () {
var request = new CSRestRequest();
request.AddParameter("user", username);
request.AddParameter("pass", password);
request.AddParameter("command", "getmyip");
var response = client.Execute(request);
return response.Content.trim();
};
this declaration appears to work
declare class CSRestRequest {
constructor (str?:any) ;
AddParameter(a:string, b:string) : any;
}
What's puzzling us at the moment is how to declare the following. The symbol is called CSSettings and it's an instance of Dictionary<string,object>, so it has some methods hanging off it, like .ContainsKey. What's the best way to declare this? It can't be newed so it's not a class with a constructor, but it does have methods like a class.
var taskName = "\XChecker\M_XChecker_" + (function () {
if (CSSettings.ContainsKey("/TEST")) {
return "TEST";
}
if (CSSettings.ContainsKey("/PRODUCTION")) {
return "PRODUCTION";
}
return "UNKNOWN";
}
()) + "_" + CSSettings("/TASKRULESETGROUPLUTFKS") + "_" + CSSettings("/INSTANCENUMBER") + "_" + CSSettings("/INSTANCECOLUMN");
LATER
The following appears to work. What's curious is that VSCode is not reporting a clash of symbol names. Can CSSetting really be a function and a namespace at the same time? Apparently, yes.
declare function CSSettings(s:string):any;
declare namespace CSSettings {
function ContainsKey(s:string):boolean;
}
declare your dictionary class. and then variable CSSettings with this type
declare class IDictionary {
constructor();
public ContainsKey(key: string): boolean;
}
declare const CSSettings: IDictionary;
CSSettings.ContainsKey('key');
// edit
so what about to create 2 type and merge it? so you will be able to use CSSettings as function and even as object
declare type functionType = (key: string) => boolean;
declare const CSSettings: functionType & { ContainsKey: (key: string) => boolean };
CSSettings.prototype.ContainsKey = 1;
CSSettings('key');
CSSettings.ContainsKey('key');
I'm creating some UI for a game I'm currently working on in C#, and want to expose everything down to Lua so that my artist can make small tweaks without needing to do anything in code. I'm using MoonSharp for integrating Lua scripts into my project.
Here is what I currently have for my UIElement wrapper class:
UIElement = {};
UIElement.__index = UIElement;
setmetatable( UIElement, {
__index = function( self, key )
local codeElement = rawget( self, "__codeElement" );
local field = codeElement and codeElement[key];
if type( field ) == "function" then
return function( obj, ... )
if obj == self then
return field( codeElement, ... );
else
return field( obj, ... )
end
end;
else
return field;
end
end,
__call = function( cls, ... )
return cls.new( ... );
end,
} );
function UIElement.new()
local self = setmetatable( {}, UIElement );
self.__codeElement = BLU_UIElement.__new();
return self;
end
BLU_UIElement is my C# class which is exposed to Lua via the MoonSharp API. It works properly when working directly with the object, and has functions like SetPos, SetColor, etc.
UIElement is intended to be my "class" in Lua to wrap and extended my C# object.
When I instantiate a UIElement elsewhere in script and attempt to call a function (SetPos for example), it does correctly get into the __index function. However, the rawget call always returns nil. It doesn't seem specific to the BLU_UIElement either. I have already tried something very simple like adding a string ID value in the constructor and trying to rawget it in the __index function, but it also returns nil.
I'm assuming I'm just doing something incorrectly setting up the metastable on either the class or the object itself, but I'm not exactly sure where the problem lies. I've been looking here: http://lua-users.org/wiki/ObjectOrientationTutorial for an idea on what I'm doing wrong, but nothing jumps out on me.
I appreciate any guidance on this, I've been looking at this for a couple days without figuring it out, and searching online generally just shows similar code to what I am already doing.
I got to admit that I am not entirely sure, what you are trying to achieve by writing your wrapper class in LUA and not C# and then expose that type but I noticed this:
For me NativeClass.__new() never worked out in MoonSharp like you are trying to do it at
self.__codeElement = BLU_UIElement.__new();
For this reason I create custom constructor-functions for my native classes and pass them to to the global namespace as delegates (Its type has to be registered though). It looks a lot like you would normally construct an object. Just without the new keyword:
In C#
public NativeClass{
public static NativeClass construct()
{
return new NativeClass();
}
}
Pass the static method as delegate to the script:
script["NativeClass"] = (Func<NativeClass>)NativeClass.construct;
Then you can create a new Instance like this in MoonSharp:
x = NativeClass()
EDIT: So didn't read that you have tried to do this with a string. Maybe you should consider not writing a wrapper class in LUA but in C# or is there a reason that forbids this?
I had a friend who is far more experienced with Lua metatables than I am take a look. Posting the answer here in case it helps anyone else.
The issue was that I was trying to use the UIElement table as both the "class" table as well as the "object" metatable. When calling rawget inside the __index function, it was attempting to find things in the UIElement table instead of the self table created in UIElement.new(). Splitting these two into distinct tables (one for the class, one for the object metatable) fixed things.
Here is my updated and working code:
UIElement = {};
setmetatable( UIElement, {
__call = function( cls, ... )
return cls.new( ... );
end,
} );
UIElement.objectMetaTable = {
__index = function( self, key )
local objectValue = rawget(self, key);
if objectValue ~= nil then
return objectValue;
end
local classValue = UIElement[key];
if classValue ~= nil then
return classValue;
end
local codeElement = rawget(self, "__codeElement");
if codeElement then
return codeElement[key];
end
end,
};
function UIElement.new()
local newInstance = setmetatable( { id = "blah" }, UIElement.objectMetaTable );
newInstance.__codeElement = BLU_UIElement.__new();
return newInstance;
end
I want to know whether passed object is actually reference of variable of specific class or not.
Consider below structure of some class 'ClassA':
public classA
{
string variable1;
int variable2;
method1(ref variable1);
}
Now if in class that contains implementation of method1(Obj object1), I want to check that 'object1' is which variable of specific 'ClassA' ?
Because I want to check in if condition like if object1 is variable1 of ClassA then //to proceed with logic....
Please provide a small example for the same.
The closest you could get to this in safe code is using expressions, but honestly you probably don't want to do this. It'd be a nightmare to try and debug, and there's probably another way to go about it. For example, is there any reason variable1 can't be of a specific type?
Now that I've spoken reason, the approach using expressions goes something like this (This is from a debugging helper, I would never use this approach in anything remotely serious. Note: A lot of exception handling and other code is stripped from this, also note how ugly and hackish it looks, that's all why you really shouldn't do this):
public static void DoStuffWithParameter<T>(Expression<Func<T>> paramExpression)
{
if (paramExpression == null) throw new ArgumentNullException("paramExpression");
var body = ((MemberExpression)paramExpression.Body);
var paramName = body.Member.Name;
var param = ((FieldInfo)body.Member)
.GetValue(((ConstantExpression)body.Expression).Value);
var declaringType = param.DeclaringType;
var paramValue = paramExpression
.Compile()
.Invoke();
if(declaringType.Equals(typeof(ClassA)))
{
//do stuff
}
}
To use that you'd use something like:
DoStuffWithParameter(()=>myClass.VarA);
I found solution. The simplest way to do this is to pass object of sender in method1 and proceed, like below.
method1(Object sender, ref Object var)
{
if(sender is classA)
{
classA senderObj= (classA) sender;
if((string)var == senderObj.variable1)
{
// Logic for variable1
}
else if((int)var == senderObj.variable2)
{
// Logic for variable2
}
. . .
}
}
ok, so in javascript, we can declare an object like this,
var obj={name:"Irshu",age:22};
console.log(obj);
How do we do the same in c#? the reason i ask because my function need to return a string and a bool together. I dont want to create a class for it, and i dont want to use the dictionary. Are there any alternatives?
public void Message(){
var obj=GetObject(val);
Messagebox.Show(Convert.ToString(obj.ind));
}
public object GetObject(string val){
return new {ind=val,flag=true};
}
This is not valid, is it?
.Net supports ExpandoObject since .NET 4.
http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject%28v=vs.110%29.aspx
It lets you declare the object and add properties as your would in javascript.
Traditionally it is for JS interop and I can't recommend it for production work. Tuple<T> is more appropriate as you get strong typing for free. Ultimately you will write less code and see less runtime errors.
What you have in your code is an anonymous type. Anonymous types cannot exist outside the scope in which they are declared. Generally, we use these for transforming LINQ results to temporary objects.
You can't return anonymous types from a method. You can do however something like this:
public void Message(){
var obj = new { ind = "oaiwejf", flag = true };
Messagebox.Show(obj.ind);
}
EDIT
Check this MSDN article
turns out, its posible, one genius on the internet posted this:
public void Message()
{
var obj=GetObject("Irshu");
var y= Cast(obj, new { ind= "", flag= true });
Messagebox.Show(y.ind); //alerts Irshu
}
public object GetObject(string val){
return new {ind=val,flag=true};
}
T Cast<T>(object obj, T type)
{
return (T)obj;
}
I need some advice on how to do the following in either C# and VB.net.
In C++, in my header file I do the following:
#define StartButtonPressed Input[0]==1 // Input is an array declared in .cpp file
In my .cpp file, i have a code something like this:
if(StartButtonPressed)
// do something
The reason of me doing so is so that my code is easier to read.
I tried the same thing in C# but it got error. How could I do the same thing in C# and VB.Net?
Please advice. Thanks.
There is no good reason to use a macro for this in C++; you could just as easily make it a function and the code would be far cleaner:
bool IsStartButtonPressed()
{
return Input[0] == 1;
}
Input should also probably be passed as an argument to the function, but it's hard to tell exactly where that is coming from.
You're best off creating a property in your class
protected bool StartButtonPressed {
get { return Input[0] == 1; }
}
then your code can be as before
.
.
.
if(StartButtonPressed) {
.
.
.
}
However for consistency with the .net framework I'd suggest calling the property IsStartButtonPressed
If you need to to be evaluated at the point of the if statement then you really need a function or a property. However is this is one time evaluation you can use a field
bool isStartButtonPressed = Input[0] ==1;
If you want may classes to have this functionality then I'd recommend a static function from another class, something like
public static class ButtonChecker {
public static bool IsPressed(int[] input) {
return input[0] == 1;
}
}
Then you call it anywhere with
if(ButtonChecker.IsPressed(Input)) {
.
.
}
But ultimately you cannot use macro's like you're used in C/C++. You shouldn't be worried about performance of properties and functions like this as the CLR jit compiler implementation is very very good for them
Here is an example program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace ConsoleApplication1 {
public static class ButtonChecker {
public static bool IsPressed(int[] input) {
return input[0] == 1;
}
}
static class Program {
public static void Main(){
int[] Input = new int[6] { 1, 0, 2, 3,4 , 1 };
for(int i = 0; i < Input.Length; ++i){
Console.WriteLine("{0} Is Pressed = {1}", i, ButtonChecker.IsPressed(Input));
}
Console.ReadKey();
}
}
}
You could use an enum
public enum buttonCode
{
startButton = 0,
stopButton = 1
// more button definitions
}
Then maybe one function
public bool IsButtonPressed(b as buttoncode)
{
return Input[b] == 1;
}
Then your calls look like:
if IsButtonPressed(buttonCode.StartButton) { }
The only changes needed to switch button codes are then in the enum, not spread across multiple functions.
Edited to Add:
If you want individually named functions, you could do this:
public bool IsStartButtonPressed()
{
return Input[buttonCode.StartButton] == 1;
}
Still, all of the edits would be in the enum, not the functions.
Bjarne Stroustrup wrote:
The first rule about macros is: Do not use them if you do not have to. Almost every macro demonstrates a flaw in the programming language, in the program, or in the programmer.
It's worth noting two things here before saying anything else. The first is that "macro" can mean a very different thing in some other languages; one would not make the same statement about Lisp. the second is that Stroustrup is willing to take his share of the blame in saying that one reason for using macros is "a flaw in the programming language", so it's not like he's just being superior in condemning their use.
This case though isn't a flaw in the programming language, except that the language lets you do it in the first place (but has to, to allow other macros). The only purpose of this macro is to make the code harder to read. Just get rid of it. Replace it with some actual C# code like:
private bool StartButtonPressed
{
get
{
return Input[0]==1
}
}
Edit:
Seeing the comment above about wanting to be faster to code, I would do something like:
private enum Buttons
{
Start = 0,
Stop = 1,
Pause = 2,
/* ... */
}
private bool IsPressed(Buttons button)
{
return Input[(int)button] == 1;
}
And then call e.g. IsPressed(Buttons.Start). Then I'd fix the C++ to use the same approach too (in C++ I would even be able to leave out the Buttons. where I wanting particularly great concision).