I keep running into the error "Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class". I'm working on a VB.NET MVC application. I have a model that has top level security Properties contained within the top level class that should be available to classes within that class. My properties always follow this structure:
Private _SecurityVar = Nothing
Public Shared Property SecurityVar
Get
If _SecurityVar = Nothing Then
_SecurityVar = User.IsInRole("SecurityFunction")
End If
Return _SecurityVar
End Get
Set(value)
End Set
End Property
My problem is is that I can't access _SecurityVar b/c it's not shared. I don't want _SecurityVar available within my view, just SecurityVar. I then need to access these top level variables from within classes that are contained within this class, such as a list of orders. I don't want to simply return User.IsInRole("SecurityFunction") because I would then be hitting the database multiple times; which would be extremely inefficient, especially when it comes to building a large table. How do I get around this, is there a better way?
Instead of sharing.. make your subclasses aware of their parentage.
In the subclass add
Private myParent as <ParentClassName>
Public Sub New(Parent as <ParentClassName>)
MyParent = Parent
End Sum
In the parent class create the subclass using
Dim Child as New <YourSubClassName>(Me)
Then when you need something from the parent in the subclass
Var = myParent.<Property Name>
If you plan on moving those subclasses around you also need to make the _Parent Public or add a method so you can change it later.
If you don't want to allow the subclass full access to the parent class you can "group" your shared variables in another class in the parent and pass that instead.
Just make your private variable shared too
Private Shared _SecurityVar = Nothing
Related
There is a class A with some private data b.
If I try to use A.b to get the data, there will be a comppilation error because I'm trying to use the dot-operator on private data.
If I write a copy-constructor for this very class A, I can use the dot-operator to get the private value b from the object I want to copy.
Why?
If you want to have access to private data you must use set and get methods, because private variables can only be accessed within the same class (an outside class has no access to it). The get method returns the variable value, and the set method sets the value.
Eg, if the instance of the class is called a and the data you want to access is called b, you can use a.getB() or a.setB(value)
I am getting confused as to how to properly set variables in a initializer, I want these to be class level variables, not instance.
And I also want to then create a single instance of another object (it is a connection object, which already has connection pooling built in, so I just need a single reference to it).
My initializer /initializers/my_class.rb
yml = YAML.load_file("#{Rails.root}/config/my_class.yml")
MYMODULE::MyClass.init(yml)
And here is my my_class.rb:
module MYMODULE
class MyClass
def self.init(yml)
#post_url = yml["defaults"]["post_url"]
end
def self.post_url
#post_url
end
# this should be a single instance
def connection_pool
# ???
end
end
end
These class level variables, how can I access them from both class methods and instance methods?
I'm getting wierd behaviour, and I'm confused as to how to reference the post_url from inside of either class methods and instance methods.
I have seen the following ways, unsure which is correct:
self.class.post_url
MyClass.post_url
#post_url
post_url
self.post_url
self.class.post_url or MyClass.post_url will work. The difference is how they work for subclasses (in the former case, subclasses will use their own version of this variable automatically, in the latter, they would share the variable in MyClass).
There is no way to directly access class instance variables from an instance: you have to call a class method which returns (or sets) them. See also: cattr_accessor.
That said, if this is really a singleton, it seems a little strange to me that you would configure part of it on the class, and then reference that info in the (single) instance. Wouldn't it make more sense just to configure this stuff on the instance? Or use a module as a singleton and not create an instance at all?
I just started BlackBerry development and I follow some of the tutorials to become familiar with the UI objects and so on and I saw/tried this:
private MenuItem menuItemClose = new MenuItem(new StringProvider("Contacts"), 0, 0) {
public void run() {
onClose();
}
};
I have not seen this way of instantiating an object before (thinking about new MenuItem), could someone explain what is happening?
And what is the difference between instantiating objects inside method definitions and in "instance variable section" like this?
That's called an "anonymous inner class."
Anonymous inner classes are classes which are created within another class but not named. They are instantiated by their interface or abstract base class definition and given their missing implementation inline with the instantiation.
In this case, MenuItem is abstract - it's missing its run() method. You're providing the implementation of its run() method here on lines 2-4.
Take a look at this JavaWorld article for more information about the various types and uses of inner classes.
As for the second part of your question "what is the difference between instantiating objects inside method definitions and in "instance variable section" like this?" -- the difference is scope, and when the object is instantiated.
Non-static member variables with initial values are created when the object which contains them is instantiated. The initial value assignment (initialization) executes at that time as well.
Static member variables with initial values are created and initialized when the class is loaded by the VM's class loader. With eager ClassLoading, this will occur at the start of the application. With lazy ClassLoading, this will occur the first time the class is referenced by the application. I believe by default most classes that aren't part of the Java runtime are loaded lazily.
Both static and non-static member variables have object-level scope and are accessible by other objects according to their access modifier (public/private/protected).
Non-static member variables are part of an object instance, and as such they are marked for garbage collection when that instance is orphaned or goes out of scope. Static member variables are only garbage collected if the class that contains them is unloaded. This only occurs if the ClassLoader instance which loaded said class is garbage collected. See this question for more info about that.
Local variables (variables which are defined within a method) with initial values are created and initialized when that line is executed as part of normal method execution. They are marked for garbage collection (destroyed) once they go out of scope (after the method in which they're contained finishes executing).
This creates an anonymous inner class which extends MenuItem and overrides the run method. It is standard Java and has nothing to do with Blackberry.
When you define a new inner class inside the method call, it's known as an 'anonymous inner class'. Anonymous inner classes are useful when you don't really need a reference to the object after the initial method call.
final Object obj = new Object(); // Standard instantiation
System.out.println(obj); // Prints java.lang.Object#5c005c
// Anonymous inner class
System.out.println(new Object() { }); // Prints Foo$1#2500250
// Anonymous inner classes work with interfaces too
new Thread(new Runnable() {
#Override
public void run() {
// Runnable is an interface
}
}).start();
This is quite a common pattern and can be useful to define 'one-time-use' objects, perhaps at the expense of readability.
I have the following code in my controller.
def index
#customer = Customer.find(params[:customer_id])
#current_orders = #customer.current_orders
#pending_orders = #customer.pending_orders
#previous_orders = #customer.previous_orders
#recurring_orders = #customer.recurring_orders
end
As you see, all the instance variables(#current_orders,#pending_orders,etc) can be obtain from #customer.
What is the best way to write this code?
Should I need to create these instance variable in controller or I just only used these through #customer variable in views.
If you reference the customer methods directly in the view you are tying the view directly to your model i.e. if for some reason you needed to change the name of the previous_orders method on customer you'd have to go through all your views and change it there, whereas with the instance variables you've used you'd only have to change it in your controllers. Using instance variables also makes your views more re-usable.
However, if you find yourself using loads of instance variables in your controllers it may be worth investigating adding another layer of abstraction in there to tidy things up.
In my opinion the example you've given is fine.
I have created a separate class (let's call it class2.cs for example) and want to use it as a level, in that when I call it, it will draw everything in one level for me. I'm having trouble getting contentmanager to work in class2. In the given Game1.cs, you can easily just go texture2d= Content.Load<Texture2D>("photo"); but I can't in class2.
I realize I have to create a new Content Manager, but it's constructor requires a game service, in which I'm not sure what I'm suppose to plug in. I currently have: ContentManager content = new ContentManager(); but I need an overload for ContentManager.
Pass Content to the constructor of your second class from the game, or you can create a Globals.cs class with static variables for your ContentManager or spriteBatch or any common resources.