I am in the process of converting some code from C# to Java. I have never used C# before, but it has been pretty easy up to this point.
I have a line that looks like this in the C# file:
coverage.createMethod = delegate (Gridpoint gp){
//Some method stuff in here, with a return objecct
}
What exactly is this trying to do? It seems a little bit like an inline class but I am not sure how to go about converting htis to java
Edit: more on the specific problem
In a file called STKDriver.java i have the following
CoverageDefinitionOnCentralBody coverage = new CoverageDefinitionOnCentralBody(...);
.
.
.
DClass value = new DClass(STKDriver.class, "invoke", CoverageGrid.class);
coverage.setGridPointCreationMethod(value);
In the fill DClass.java, which extends CreateCoverageGridPointForAccess I have the following:
public DClass(Class class1, String string, Class<CoverageGridPoint> class2{}
.
.
.
public IServiceProvider invoke(CoverageGridPoint gridPoint){
return something; //of the classtype Platform
}
Is this done correctly? The class definitions are linked here:
http://www.agi.com/resources/help/online/AGIComponentsJava/index.html?page=source%2FWhatsNewJava.html
Notice that the class CreateCoverageGridPointForAccess is abstract and extends that Delegate class.
Does this implementation I have created look correct? I Can write in more code if necessary
This is an anonymous method in C#. It's technically the same thing as:
coverage.createMethod = new Func<Gridpoint, object>(SampleMethod);
public object SampleMethod(Gridpoint gp)
{
return thingy; // Pseudo for return value
}
It's just a shortcut you can use to code less.
Tejs' answer is correct. However be careful because anonymous functions can use closures which means using an existing local variable declared in the outer function, from the anonymous delegate. I'm no Java programmer so I don't know if Java supports this.
coverage.createMethod is a Delegate.
The following code creates an anonymous method and assigns it to the delegate:
coverage.createMethod = delegate (Gridpoint gb) {
}
so that when somebody calls coverage.createMethod, your anonymous method gets executed.
Related
I'm creating code by using CodeDom. However, CodeDom does not support lambda statements. So I'm now trying to mimic a lambda statement by creating a local method and pass on the method as a parameter to another method. Like so:
public string MainMethod(string myParameter)
{
string g() { return instance.MainMethod(myParameter); }
return someOtherMethod(g);
}
The method 'MainMethod' is already generated by using CodeDom
and I'm trying to get the local method in there. However, I cannot find a way to do that up to this point. I could use some help with that.
I already tried adding a CodeMemberMethod to a CodeMemberMethod but there seems to be no way to do that. I cannot seem to find any alternatives.
Currently my CodeDom code is using MethodInfo as a base:
var method = new CodeMemberMethod();
method.Name = methodInfo.Name;
method.ReturnType = new CodeTypeReference(methodInfo.ReturnType);
//left out parameter stuff
var gMethod = new CodeMemberMethod() { Name = "g", ReturnType = new CodeTypeReference(methodInfo.ReturnType) };
gMethod.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("instance"), methodInfo.Name), parameterReferences.ToArray())));
method.Statements.Add(gMethod);
Now, the pain is in the last statement. I'm actually trying to add a CodeMemberMethod to a CodeMemberMethod, which is not allowed via the Statements property. Is there any way to do that in another way?
Local functions were not a supported language construct until C# version 7. CodeDOM was designed much earlier and does not cover all C# feature, even of the then-current version of C#. In other words, there is, unfortunately, no way to declare a “local method” and add it to the Statements collection of another method.
Instead, consider declaring a separate private method. Your class's public interface will remain unaffected and, most likely, you will achieve what you want. However, no implicit access to the 'outer method's' parameters will be possible.
Also, consider looking at this answer for further ideas.
I am trying to learn how to write a simple scripting language on top of DLR, by playing with a very old DLR example called ToyScript. However ToyScript does not seem to support the following structure of a script, which I would like to use in my implementation :
print b()
def b() {
return 1
}
It raises an exception, exactly as in most statically compiled languages.'
If the script follows a "static languages paradigm" :
def b() {
return 1
}
print b()
ToyScript works without problems.
My question is : how the former should be done in DLR ?
[Obviously I am looking for a description of a solution, and not for a solution itself :)]
There are a few possible implementations. The first is to require an execution to create a function. With this way, you cannot invoke a function before a function is created with an execution. The second way is to create the all the functions when you parse the code and execute the global scripts. With this way, function declaration can appear anywhere in the code because the functions are already created before any execution. The draw back is that you need to create all the functions no matter you invoke them or not. Then there is an in-between way; when you parse the code for the first time, you store the abstract syntax tree (AST) of the functions in a function table. Then when you want to invoke a function, look for the function declaration in the function table and then compile or interpret from the AST. Compare the following two JavaScript snippets and you will have a good idea.
console.log(b());
function b() {
return 1;
}
and
console.log(b());
var b = function() {
return 1;
}
As part of a personal project I am working on I took a small codebase written by another programmer and was trying to refactor it to my own purposes. Long story short, they had this huge section of code that was an incoming command parser. I moved the code to it's own class file and moved several code bits to their own methods in that class. The problem I'm encountering is that I can't pass two needed objects from the original block of code to the new parser class. The orginal code section uses an mutliple-method object called AllSockets. I can't seem to figure out how to pass this object to the new class method without getting the error
Error 2 Argument 2: cannot convert from 'method group' to 'object'
The invoking line of code:
bool wasValidCommand = (commandParser.CheckForCommands(thisConnection, AllSockets, characterPath, helpFilePath));
The method invoked:
public bool CheckForCommands(ConnectionInfo _connected, object _AllSockets, string characterPath, string helpFilePath)
I've posted the hosting Server.cs class here: http://codepad.org/1kRHA1nk
The new class I am trying to pass the object to is here: http://codepad.org/oONRaEtt
Warning: The code is really hacked together right now and variable naming is a nightmare. I can paste the specific sections if that would be easier to read. Any help would be appreciated.
The AllSocket method is declared as
public object AllSockets(string tempFlag, object objectOne, object object_Two, object object_Three)
From a quick look over the code, it appears AllSockets is used in the private Shout(..) method of the class - as method. So in order to pass this as a function object, you may declare the CheckForCommands method with a parameter of type delegate or Function:
delegate object AllSocketDelegate (string tempFlag, object objectOne, object object_Two, object object_Three);
public bool CheckForCommands(ConnectionInfo _connected, AllSocketDelegate _AllSockets, string characterPath, string helpFilePath)
or similar with the Func instead of a delegate.
Replace object _AllSockets with:
Func<string, object, object, object, object>_AllSockets
You should probably replace this in CheckForCommands, Shout and Tell method signatures.
AllSockets is a method. I'm guessing you want to take the object that the AllSockets method returns and pass that into the commandParser.CheckForCommands function.
Try something like:
object allSockets = AllSockets(...);
bool wasValidCommand = (commandParser.CheckForCommands(thisConnection, allSockets, characterPath, helpFilePath));
Reading a book (VS 2010), it says that commands (statements) in .NET Csharp cannot exist outside of method.
I am wondering - field declaration etc, these are commands, are they not? And they exist at class level. Can somebody elaborate at this a bit?
If you mean:
class Foo
{
int count = 0;
StringBuilder buffer = new StringBuilder();
}
The count and buffer are declarations using initializer expressions . But this code contains no statements.
A field initialiser is written with the code outside a method, but the compiler puts that code inside the constructor.
So a field initialiser like this:
class Foo {
int Bar = 42;
}
is basiclally a field and an initialiser in the constructor:
class Foo {
int Bar;
Foo() {
Bar = 42;
}
}
There's no such concept as a "command" in C#.
And a static / instance variable declaration isn't categorized as a statement within C# - it's a field-declaration (which is a type of class-member-declaration) as per the C# spec. See section 10.5 of the C# 4 spec for example.
Now the statements which declare local variables are statements, as defined by declaration-statement in the spec (section 8.5). They're only used for locals though. See section B.2.5 for a complete list of statement productions within C# 4.
Basically, the C# spec defines the terminology involved - so while you might think informally of "commands" and the like, in a matter of correctness the C# spec is the source of authority. (Except for where it doesn't say what the language designers meant to say, of course. That's pretty rare.)
As you said they're declarations, a statement is one which actually gets something done.
No, they're declarations. Class member declarations, to be precise.
And it's perfectly legal for those to exist outside of a method. Otherwise, you couldn't declare a method in the first place!
By "statements", the book is telling you that you can't have things like method calls outside of a method. For example, the following code is illegal:
public void DoSomething()
{
// Do something here...
}
MessageBox.Show("This statement is not allowed because it is outside a method.");
Classes, namespace, fields declarations are not declarations statements.
A field can be initialised outside a method with an expression but while an expression is a statement there are lots of statements that are not expressions (eg. if).
It all comes down to how the language grammar defines the terms, and the way C# does it is pretty common (eg. very similar to C and C++).
This question already has answers here:
Closed 14 years ago.
Duplicate: Function overloading by return type?
Maybe this is a very silly question but I don't understand why I can't declare two methods that have the same signature when they have different return types.
public class MyClass
{
private double d = 0;
public double MyMethod()
{
return d;
}
public string MyMethod()
{
return d.ToString();
}
}
I get a compile error that states that the class already defines a member with the same parameter types.
(Obviously the way I'm using this in my code isn't as simple as my example code...but I think it gets the idea across.)
Am I missing something concerning OO design that makes what I'm trying to do an OOP anti-pattern? Surely the compiler should be able to determine which method I'm trying to use as long as I specifically tell it which one I want.
Given MyClass myClass = new MyClass(); I would expect the following code to work:
double d = myClass.MyMethod();
string s = myClass.MyMethod();
I would expect the following code to have problems:
var v = myClass.MyMethod();
But even in the case of var it should result in a compile error.
Can anyone see what I'm doing wrong here? I'm more than happy to be corrected. :-)
It's because of type coercion.
Say you have the following functions:
int x(double);
float x(double);
double y = x(1.0);
Now, which of the two prototypes should you call, especially if they do two totally different things?
Basically, a decision was made early on in the language design to only use the function name and arguments to decide which actual function gets called, and we're stuck with that until a new standard arrives.
Now, you've tagged your question C# but I see nothing wrong with designing a language that can do what you suggest. One possibility would be to flag as an error any ambiguous commands like above and force the user to specify which should be called, such as with casting:
int x(double);
float x(double);
double y = (float)(x(1.0)); // overload casting
double y = float:x(1.0); // or use new syntax (looks nicer, IMNSHO)
This could allow the compiler to choose the right version. This would even work for some issues that other answers have raised. You could turn the ambiguous:
System.out.Println(myClass.MyMethod());
into the specific:
System.out.Println(string:myClass.MyMethod());
This may be possible to get added to C# if it's not too far into a standards process (and Microsoft will listen) but I don't think much of your chances getting it added to C or C++ without an awfully large amount of effort. Maybe doing it as an extension to gcc would be easier.
There's nothing from stopping you from calling your method without "capturing" the return type. There's nothing from stopping you from doing this:
myClass.MyMethod();
How will the compiler know which one to call in that case?
Edit: Adding to that, in C# 3.0, when you can use var, how will the compiler know which method you're calling when you do this:
var result = myClass.MyMethod();
Because the return type isn't all that important when calling a method. It would lead to ambiguity in many cases to have methods only differing by return type. You might not store the result in a variable at all, or do something like this:
System.out.Println(myClass.MyMethod());
The compiler would have no way to figure out, which of the methods you wanted to call.
A method signature is the name and input parameters (type & order) only. The return type is not part of the signature. Thus two methods with the same name and input parameters are identical and conflict with each other.
What, if any, variable you're assigning the method to can't inform the compiler which method to use. Imagine:
String message = "Result = " + myClass.MyMethod();